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);
}
}
You should able to escape the special character using java.util.regex.Pattern.quote
By changing
to