java.util.regex.PatternSyntaxException:Unmatched closing';)';:在string.split操作期间
我正在尝试执行类似于以下内容的拆分:java.util.regex.PatternSyntaxException:Unmatched closing';)';:在string.split操作期间,java,regex,split,Java,Regex,Split,我正在尝试执行类似于以下内容的拆分: String str = "({Somestring 1 with a lot of braces and commas}),({Somestring 12with a lot of braces and commas})"; println str.split("}),({"); 但我明白了: java.util.regex.PatternSyntaxException:索引0附近的不匹配结尾“') }),({ 显然,我的字符串被视为正则表达式 有什么方
String str = "({Somestring 1 with a lot of braces and commas}),({Somestring 12with a lot of braces and commas})";
println str.split("}),({");
但我明白了:
java.util.regex.PatternSyntaxException:索引0附近的不匹配结尾“')
}),({
显然,我的字符串被视为正则表达式
有什么方法可以转义这个字符串吗?字符(
和)
和{
和}
是regexp中的特殊字符。必须转义这些字符:
println str.split("\\}\\),\\(\\{");
除了手动转义字符串,您还可以将其视为文本,而不是正则表达式:
println str.split(Pattern.quote("}),({"));
正则表达式中必须转义的Java字符是:
.[]{}()*+-^$|
用法:str.split(“}\\”,\\({”)
实际上,{}不需要在正则表达式中转义。
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);
}