如何查找包含括号“(”并使用单词边界的单词?

发布于 2024-10-21 21:08:16 字数 585 浏览 0 评论 0原文

我正在大文本中寻找短语“成功(并从失败中学习!)”。由于有括号,我使用 quote(...) 来允许它,但我也想使用单词边界“\b”,因此如果在这样的文本“Kin successes(并从他们的经验中学习)中找到该短语,它将被忽略失败!)”。

这是我的代码:

String phrase = Pattern.quote( "in successes (and learn from their failures!)" );   
Pattern myPattern = Pattern.compile( "\\b" + phrase + "\\b" );  // Use word boundary(\b) = No letters after it.
Matcher myMatcher = myPattern.matcher( bigText );
myMatcher.find();  // Returns false.

如上所述,由于使用“\b”,此代码将返回 false。如果我省略“\b”,匹配器将返回 true。 有没有办法在使用两个条件时解决这个问题:quote(...) + "\b"?

I am looking for a phrase "in successes (and learn from their failures!)" in a big text. Since there are brackets i have used quote(...) to allow it, but i also want to use word boundaries "\b" so this phrase will be ignored if it was found in such text "Kin successes (and learn from their failures!)".

Here is my code :

String phrase = Pattern.quote( "in successes (and learn from their failures!)" );   
Pattern myPattern = Pattern.compile( "\\b" + phrase + "\\b" );  // Use word boundary(\b) = No letters after it.
Matcher myMatcher = myPattern.matcher( bigText );
myMatcher.find();  // Returns false.

As mentioned this code will return false because of using "\b". If i omitted "\b" the matcher will return true. Is there a way to fix this while using the 2 conditions: quote(...) + "\b" ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

指尖凝香 2024-10-28 21:08:16

我认为最好的选择是删除第二个 \b:

Pattern myPattern = Pattern.compile( "\\b" + phrase);

phrase!) 结尾,它们不是单词字符,并且应该适合所有情况,例如:失败!),以及更多失败!)失败!)或不

如果你想要为了确保它后面没有另一个字母,您可以使用“\\b”+短语+“\\B”,但我不确定这里是否需要它。

The best option here in my opinion is to drop the second \b:

Pattern myPattern = Pattern.compile( "\\b" + phrase);

phrase ends with !), which aren't word characters, and should match well for all cases, for example: failures!), and more, failures!), failures!)or not

If you want to make sure it isn't followed by another letter you can use "\\b" + phrase + "\\B", but I'm not sure it's needed here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文