java.util.regex.PatternSyntaxException:不匹配的关闭')':在string.split操作期间

问题描述 投票:0回答:4

我正在尝试执行类似于以下的拆分:

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 附近不匹配的结束 ')' }),({

显然,我的字符串被视为正则表达式。

有什么办法可以转义这个字符串吗?

java regex split
4个回答
16
投票

字符

(
)
以及
{
}
是正则表达式中的特殊字符。你必须逃避这些:

println str.split("\\}\\),\\(\\{");

5
投票

您也可以将其视为文字而不是正则表达式,而不是手动转义字符串:

println str.split(Pattern.quote("}),({"));

2
投票

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);
    }

0
投票
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());
            }
© www.soinside.com 2019 - 2024. All rights reserved.