user2825125
user2825125

Reputation: 91

Why is there a PatternSyntax Excpetion for the following program?

I am getting a Pattern Syntax Exception for the following program. I have escaped the backslashes by using "\\", but there is a still an exception saying:

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 1
\left(

^

Here is the code:

String[] paren = {"\\big(","\\Big(","\\bigg(","\\Bigg(","\\left("};
for(String x : paren){
    if(line.contains(x))
        line=line.replaceAll(x, "("); //error on this line
}

Thanks.

Upvotes: 1

Views: 2459

Answers (2)

Pshemo
Pshemo

Reputation: 124275

If your goal is to replace each of literals "\\big(", "\\Big(", "\\bigg(", "\\Bigg(", "\\left(" then avoid using replaceAll because it uses regex as first argument representing value which should be replaced. In your case strings you want to replace contain regex metacharacters like ( or anchors like \\b \\B so even if this would not throw Exception you would not get results you wanted.

Instead use replace (without All suffix) method which will automatically escape all regex metacharacters, so you will avoid problems like unescaped (.

So try with

String[] paren = {"\\big(","\\Big(","\\bigg(","\\Bigg(","\\left("};
for(String x : paren){
    if(line.contains(x))
        line=line.replace(x, "("); 
}

Upvotes: 0

Bart Kiers
Bart Kiers

Reputation: 170257

\l is an invalid escape sequence and you have unescaped (.

Note that if you want to match a literal backslash, you need to double escape it, and then escape those again because it all resides inside a string literal. That is why "\\l" is being parsed as the regex pattern \l (which is an invalid escape sequence). And "\\b" and "\\B" are parsed as the escape sequences \b and \B which are word- and non-word boundaries.

Assuming you would like to match the literal backslash, try this instead:

{"\\\\big\\(","\\\\Big\\(","\\\\bigg\\(","\\\\Bigg\\(","\\\\left\\("};

but then, your contains(...) call won't work anymore!

Or perhaps better/safer, let Pattern quote/escape your input properly:

String[] paren = {"\\big(","\\Big(","\\bigg(","\\Bigg(","\\left("};

for(String x : paren){

    if(line.contains(x)) {

        line = line.replaceAll(Pattern.quote(x), "(");
    }
}

Upvotes: 2

Related Questions