如何匹配带有括号的模式?
我试图在大文本中查找特定短语,但该短语可能包含“[”、“(”、“*”等字符,...如“name1 (name2”),但它查找它时会导致无效异常。这是我的代码:
Pattern myPattern = Pattern.compile( "\\b" + phrase + "\\b" ); // Exception
Matcher myMatcher = myPattern.matcher( largeText );
我尝试使用 quote(...) 来修复此类字符,但它不起作用:
phrase = Pattern.quote( phrase );
如何修复此问题以允许此类字符?< /强>
I am trying to look for specific phrase inside large text, but the phrase may contain characters like "[", "(", "*", ... like "name1 (name2", but it causes an invalid exception when looking for it. Here is my code :
Pattern myPattern = Pattern.compile( "\\b" + phrase + "\\b" ); // Exception
Matcher myMatcher = myPattern.matcher( largeText );
I have tried to use quote(...) to fix such characters but it didn't work :
phrase = Pattern.quote( phrase );
How can i fix this to allow such characters ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Pattern.quote(phrase)
工作得很好:打印:
Pattern.quote(phrase)
works just fine:prints:
处理短语以转义所有可能的正则表达式元字符。
Process phrase to escape all possible regex metacharacters.
您能否提供一个重现此问题的完整示例?我已经尝试了以下方法,效果很好:
输出是:
Could you please provide a complete example that reproduces this problem? I've tried the following and it works fine:
The output is:
您可能只想使用:
来测试子字符串的存在/偏移量。
要使用模式,这应该可行:
但是使用 * 和 ? 时有一个小问题。在短语的开头或结尾。
这些字符被视为空白字符(不是单词字符),因此如果它们出现在短语的开头或结尾,则为了匹配边界,它们必须包含所有前导/尾随空白。
如果短语的开头或结尾有这些字符,您可能需要通过删除“\b”来特殊处理。
You may want to just use:
to test the existence/offset of a substring.
To use patterns, this should work:
But there's a little problem when using * and ? at the start or end of the phrase.
Those characters are treated like white space characters (not word characters) so if they appear at the beginning or end of a phrase, then to match the boundary they must include all the leading/trailing whitespace.
You may need to special case this by dropping the "\b" if the phrase has those characters at the start or end.