java.util.regex.PatternSyntaxException:不匹配的关闭 ')' :在 string.split 操作期间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30839697/
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.util.regex.PatternSyntaxException: Unmatched closing ')' : during string.split operation
提问by Abhidemon
I am trying to perform a split similar the following:
我正在尝试执行类似于以下内容的拆分:
String str = "({Somestring 1 with a lot of braces and commas}),({Somestring 12with a lot of braces and commas})";
println str.split("}),({");
But i see:
但我看到:
java.util.regex.PatternSyntaxException: Unmatched closing ')' near index 0 }),({
java.util.regex.PatternSyntaxException: 索引 0 附近不匹配的关闭 ')' }),({
Clearly , my string is being treated as a regular expression.
显然,我的字符串被视为正则表达式。
Is there a way i can escape this string?
有没有办法可以转义这个字符串?
回答by Jens
the character (
and )
and {
and }
are special character in regexp. you have to escape these:
字符(
和)
和{
和}
是正则表达式中的特殊字符。你必须逃避这些:
println str.split("\}\),\(\{");
回答by assylias
Instead of escaping the string manually you can also treat it like a literal as opposed to a regex with:
除了手动转义字符串,您还可以将其视为文字而不是正则表达式:
println str.split(Pattern.quote("}),({"));
回答by Ankur Singhal
Java characters
that have to be escaped
in regular expressions
are:
Java characters
必须escaped
在regular expressions
:
.[]{}()*+-?^$|
.[]{}()*+-?^$|
public static void main(String[] args) {
String str = "({Somestring 1 with a lot of braces and commas}),({Somestring 12with a lot of braces and commas})";
String[] array = str.split("\}\),\(\{");
System.out.println(array.length);
}