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!
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 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*");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With