7

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 }),({

Clearly , my string is being treated as a regular expression.

Is there a way i can escape this string?

1
  • 1
    Use: str.split("}\\),\\({") Commented Jun 15, 2015 at 7:39

4 Answers 4

17

the character ( and ) and { and } are special character in regexp. you have to escape these:

println str.split("\\}\\),\\(\\{");
Sign up to request clarification or add additional context in comments.

Comments

4

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("}),({"));

Comments

2

Java characters that have to be escaped in regular expressions are:

.[]{}()*+-?^$|

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

1 Comment

Actually, {} does not need to be escaped in regex.
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());
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.