java 字符串拆分问题使用“*”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1308137/
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
String split question using "*"
提问by OHHAI
Let's say have a string...
假设有一个字符串...
String myString = "my*big*string*needs*parsing";
All I want is to get an split the string into "my" , "big" , "string", etc. So I try
我想要的只是将字符串拆分为 "my" 、 "big" 、 "string" 等。所以我尝试
myString.split("*");
returns java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
返回 java.util.regex.PatternSyntaxException:在索引 0 附近悬空的元字符 '*'
*is a special character in regex so I try escaping....
*是正则表达式中的一个特殊字符,所以我尝试转义....
myString.split("\*");
same exception. I figured someone would know a quick solution. Thanks.
同样的例外。我想有人会知道一个快速的解决方案。谢谢。
回答by Jo?o Silva
split("\\*")works with me.
split("\\*")和我一起工作。
回答by akf
One escape \will not do the trick in Java 6 on Mac OSX, as \is reserved for \b \t \n \f \r \'\"and \\. What you have seems to work for me:
一个转义\在 Mac OSX 上的 Java 6 中不起作用,这\是为\b \t \n \f \r \'\"和保留的\\。你所拥有的似乎对我有用:
public static void main(String[] args) {
String myString = "my*big*string*needs*parsing";
String[] a = myString.split("\*");
for (String b : a) {
System.out.println(b);
}
}
outputs:
输出:
my
big
string
needs
parsing
我的
大
字符串
需要
解析
回答by Dirk
回答by jatanp
myString.split("\\*");is working fine on Java 5. Which JRE do you use.
myString.split("\\*");在 Java 5 上运行良好。您使用哪种 JRE。
回答by Milhous
You can also use a StringTokenizer.
您还可以使用StringTokenizer。
StringTokenizer st = new StringTokenizer("my*big*string*needs*parsing", "\*");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
回答by Pavithra Gunasekara
This happens because the split method takes a regular expression, not a plain string.
发生这种情况是因为 split 方法采用正则表达式,而不是普通字符串。
The '*' character means match the previous character zero or more times, thus it is not valid to specify it on its own.
'*' 字符表示匹配前一个字符零次或多次,因此单独指定它是无效的。
So it should be escaped, like following
所以它应该被转义,就像下面
split("\\*")
split("\\*")

