joshft91
joshft91

Reputation: 1885

regex Illegal repetition

I have a string array of operators that I am iterating through. When I find one that exists in strLine, I replace the first instance of it with a blank string. When I get to the {, I get the java.util.regex.PatternSyntaxException: Illegal repetition.

Now, I know that the { is a special java operator so that is the reason it is failing. What would be the best way to escape this character with the setup I have now?

String[] operators = {".", ",", "{", "}", "!", "++", "--", "*", "/", "%", "+", "-", "<"}

String strLine = "for (int count = input.length(); count > 0; count--) {";
strLine = strLine.trim();

for (int i = 0; i < operators.length; i++) {
    if(strLine.contains(operators[i])) {

        strLine = strLine.replaceFirst(operators[i]+"\\s*", "");
        System.out.println("Removal of: " + operators[i]);
        System.out.println("Sentence after removal: " + strLine);
    }
}

Upvotes: 0

Views: 217

Answers (2)

tuga
tuga

Reputation: 331

You have to escape each regex reserved operator with a backslash. So you need to put two backslashes (the other one is to escape the backslash itself). Example: "\\.", "\\{"

Upvotes: 0

jmkelm08
jmkelm08

Reputation: 687

You should able to escape the special character using java.util.regex.Pattern.quote

By changing

strLine = strLine.replaceFirst(operators[i]+"\\s*", "");

to

strLine = strLine.replaceFirst(Pattern.quote(operators[i])+"\\s*", "");

Upvotes: 1

Related Questions