博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java Regex Pattern Syntax Exception
阅读量:2242 次
发布时间:2019-05-09

本文共 1429 字,大约阅读时间需要 4 分钟。

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.

转载地址:http://taebb.baihongyu.com/

你可能感兴趣的文章
牛客网题目1:最大数
查看>>
散落人间知识点记录one
查看>>
Leetcode C++ 随手刷 547.朋友圈
查看>>
手抄笔记:深入理解linux内核-1
查看>>
内存堆与栈
查看>>
Leetcode C++《每日一题》20200621 124.二叉树的最大路径和
查看>>
Leetcode C++《每日一题》20200622 面试题 16.18. 模式匹配
查看>>
Leetcode C++《每日一题》20200625 139. 单词拆分
查看>>
Leetcode C++《每日一题》20200626 338. 比特位计数
查看>>
Leetcode C++ 《拓扑排序-1》20200626 207.课程表
查看>>
Go语言学习Part1:包、变量和函数
查看>>
Go语言学习Part2:流程控制语句:for、if、else、switch 和 defer
查看>>
Go语言学习Part3:struct、slice和映射
查看>>
Go语言学习Part4-1:方法和接口
查看>>
Leetcode Go 《精选TOP面试题》20200628 69.x的平方根
查看>>
leetcode 130. Surrounded Regions
查看>>
【Python】详解Python多线程Selenium跨浏览器测试
查看>>
Jmeter之参数化
查看>>
Shell 和Python的区别。
查看>>
【JMeter】1.9上考试jmeter测试调试
查看>>