我正在尝试执行类似于以下的拆分:
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 附近不匹配的结束 ')' }),({
显然,我的字符串被视为正则表达式。
有什么办法可以转义这个字符串吗?
字符
(
和 )
以及 {
和 }
是正则表达式中的特殊字符。你必须逃避这些:
println str.split("\\}\\),\\(\\{");
您也可以将其视为文字而不是正则表达式,而不是手动转义字符串:
println str.split(Pattern.quote("}),({"));
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);
}
try {
while ((line = readSql.readLine()) != null) {
if (!line.trim().startsWith("--")) {
Log.i("line = ", line);
try {
dbInserts.execSQL(line.replaceAll(", ''\\);", " );"));
} catch (SQLException sqlException) {
dbInserts.execSQL(line);
}
}
}
} catch (Exception e) {
Log.i("Exception line = ", e.toString());
}