java 使用 String.split() 在双管 (||) 上拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15524566/
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
Splitting a string on the double pipe(||) using String.split()
提问by FarSh018
I'm trying to split the string with double pipe(||) being the delimiter.String looks something like this:
我试图用双管(||)作为分隔符来分割字符串。字符串看起来像这样:
String str ="[email protected]||[email protected]||[email protected]";
i'm able to split it using the StringTokeniser.The javadoc says the use of this class is discouraged and instead look at String.split as option.
我可以使用 StringTokeniser 拆分它。javadoc 说不鼓励使用此类,而是将 String.split 视为选项。
StringTokenizer token = new StringTokenizer(str, "||");
The above code works fine.But not able to figure out why below string.split function not giving me expected result..
上面的代码工作正常。但无法弄清楚为什么下面的 string.split 函数没有给我预期的结果..
String[] strArry = str.split("\||");
Where am i going wrong..?
我哪里出错了..?
回答by gtgaxiola
You must escape every single |
like this str.split("\\|\\|")
你必须|
像这样逃离每一个str.split("\\|\\|")
回答by Gijs Overvliet
String.split()
uses regular expressions. You need to escape the string that you want to use as divider.
String.split()
使用正则表达式。您需要转义要用作分隔符的字符串。
Pattern has a method to do this for you, namely Pattern.quote(String s)
.
Pattern 有一种方法可以为您执行此操作,即Pattern.quote(String s)
.
String[] split = str.split(Pattern.quote("||"));
回答by BlackJoker
try this bellow :
试试这个:
String[] strArry = str.split("\|\|");
回答by Sarath Kumar Sivan
You can try this too...
你也可以试试这个...
String[] splits = str.split("[\|]+");
Please note that you have to escape the pipe since it has a special meaning in regular expression and the String.split() method expects a regular expression argument.
请注意,您必须对管道进行转义,因为它在正则表达式中具有特殊含义,并且 String.split() 方法需要一个正则表达式参数。
回答by passionatedevops
Try this
试试这个
String yourstring="Hello || World";
String[] storiesdetails = yourstring.split("\|\|");