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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值