java 如何使用 String.split() 拆分字符串而没有尾随/前导空格或空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10147599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I split string using String.split() without having trailing/leading spaces or empty values?
提问by expert
How do I split string using String.split() without having trailing/leading spaces or empty values?
如何使用 String.split() 拆分字符串而没有尾随/前导空格或空值?
Let's say I have string such as " [email protected] ; [email protected]; [email protected], [email protected] "
.
假设我有诸如" [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.
我曾经通过调用来分割它,String.split("[;, ]+")
但缺点是你会得到空数组元素,你需要在额外的循环中忽略这些元素。
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:
我还尝试过String.split("\\s*[;,]+\\s*")
which 不提供空元素,但在第一封电子邮件中留下前导空格,在最后一封电子邮件中留下尾随空格,因此结果数组看起来像因为这些电子邮件旁边没有逗号或分号:
[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())?
是否可以仅使用正则表达式和拆分(不使用对 String.trim() 的额外调用)来获取“干净”电子邮件数组?
Thanks!
谢谢!
回答by Michael
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.
我假设您非常确定您的输入字符串只包含电子邮件地址,并且只需要修剪/重新格式化。
回答by Eugene Retunsky
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).
但是它在开头给出了一个空字符串(仅使用 split 无法摆脱它)。
Thus only something like this can help:
因此,只有这样的事情可以帮助:
String.trim().split("\s*(;|,)\s*");
回答by Louis Wasserman
回答by DGomez
Try using String.trim()
in the result of the split
尝试String.trim()
在分割的结果中使用
回答by Robson Fran?a
First of all, as DGomez pointed out:
首先,正如 DGomez 指出的那样:
String.trim()
Use that in the input string, so the leading and trailing spaces are gone.
在输入字符串中使用它,因此前导和尾随空格都消失了。
Now, use this regex for splitting the emails:
现在,使用此正则表达式拆分电子邮件:
String.split("[,;]+\s*")
I think this should do it.
我认为应该这样做。