Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split string using String.split() without having trailing/leading spaces or empty values?

Tags:

java

regex

How do I split string using String.split() without having trailing/leading spaces or empty values?

Let's say I have string such as " [email protected] ; [email protected]; [email protected], [email protected] ".

I used to split it by calling String.split("[;, ]+") but drawback is that you get empty array elements that you need to ignore in extra loop.

I also tried String.split("\\s*[;,]+\\s*") which doesn't give empty elements but leaves leading space in first email and trailing space in last email so that resulting array looks like because there are no commas or semicolons next to those emails:

[0] = {java.lang.String@97}"  [email protected]"
[1] = {java.lang.String@98}"[email protected]"
[2] = {java.lang.String@99}"[email protected]"
[3] = {java.lang.String@100}"[email protected]  "

Is it possible to get array of "clean" emails using only regex and Split (without using extra call to String.trim()) ?

Thanks!

like image 330
expert Avatar asked Apr 13 '12 20:04

expert


2 Answers

String input = " [email protected] ; [email protected]; [email protected], [email protected] ";
input = input.replace(" ", "");
String[] emailList = input.split("[;,]+");

I'm assuming that you're pretty sure your input string contains nothing but email addresses and just need to trim/reformat.

like image 70
Michael Avatar answered Sep 27 '22 17:09

Michael


Like this:

String.split("\\s*(;|,|\\s+)\\s*");

But it gives an empty string in the beginning (no way to get rid of it using only split).

Thus only something like this can help:

String.trim().split("\\s*(;|,)\\s*");
like image 37
Eugene Retunsky Avatar answered Sep 27 '22 16:09

Eugene Retunsky