Java Regex Pattern Syntax Exception

Java Regex Pattern Syntax Exception


java.util.regex.PatternSyntaxException: Unmatched closing ')'


I don't immediately see what's wrong with your regex code although I suspect the problem would be apparent if we knew the values for toCensor and word. I've rewritten your code as follows:

String toCensor = "some sentence that uses frack word";
String word = "frack";
String replaceWith = "f#@!ck";
String regex = new StringBuilder("(?i)").append(word).toString();
toCensor = toCensor.replaceAll(regex, replaceWith);
So you are trying to run a regular expression across toCentor and do a case-insensitive match (that's the (?i) flag) looking for word. One problem is that if word has any special regex characters, they will be treated as part of the pattern. I think that's you bug. For example if you try this:

String word = ")ick";
You'd get the error:

Unmatched closing ')' near index 4    (?i))ick
This is similar but not exactly what you are seeing. You can turn off regex pattern compilation by wrapping the word in `"\Qword\E". For example:

String regex = new StringBuilder("(?i)\\Q").append(word).append("\\E").toString();
toCensor = toCensor.replaceAll(regex, replace);
'\Q' in the pattern turns on "quoting" and \E is the end of it. See also Pattern.quote(). You can also fix this by doing better sanity checking of the input to make sure that they are whole words. I suspect that ) is not a proper character to be censored.


你可能感兴趣的:(JavaScript)