Java 拆分分隔符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13276563/
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
Java Split Delimiter
提问by user1720281
If I want to have a delimiter which can separate by delimiter //, how can I implement it?
如果我想要一个可以用分隔符分隔的分隔符//,我该如何实现呢?
For example:
例如:
String str="i have a ball // do i /g f y"
I want the delimiter to be "//"
, therefore the result will be:
我希望分隔符为"//"
,因此结果将是:
"do i /g f y"
回答by óscar López
The string "//"
can be used directly as a separator, it doesn't need escaping:
字符串"//"
可以直接用作分隔符,不需要转义:
String[] data = str.split("//");
A different situation occurs with "\\"
, the '\'
character is used as escape character in a regular expression and in turn it needs to be escaped by placing another '\'
in front of it:
出现不同的情况"\\"
,该'\'
字符在正则表达式中用作转义字符,反过来需要通过'\'
在其前面放置另一个来进行转义:
String[] data = str.split("\\");
回答by bobah
If you just need the tail, as you specified in the question, then you don't need to split, but rather:
如果您只需要尾巴,正如您在问题中所指定的那样,那么您不需要拆分,而是:
result = str.substring(str.indexOf("//") + 2);
回答by 16dots
Code:
代码:
String testString = "dog//cat//meow/ok";
String[] tokens = testString.split("//");
for(String token: tokens){
System.out.println(token);
}
Output:
输出:
dog
cat
meow/ok
回答by John Gardner
theString.split( "//" );
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)
since the arg is a regex, it might require some escaping, but that should work.
由于 arg 是一个正则表达式,它可能需要一些转义,但这应该有效。
回答by manisha mulchandani
Here No Escaping is required as the code is having string with "//" backslashes not "\" forward slashes.
这里不需要转义,因为代码的字符串带有“//”反斜杠而不是“\”正斜杠。
Code here works fine:
这里的代码工作正常:
String str="i have a ball // do i /g f y";
String ss[]=str.split("//");
System.out.println(ss[0]);
System.out.println(ss[1]);
OUTPUT:
输出:
i have a ball
do i /g f y
我有一个球
我 /gfy