我有正则表达式来检查某些文本是否包含单词(忽略边界)
String regexp = ".*\\bSOME_WORD_HERE\\b.*";
但当“SOME_WORD”以#(井号标签)开头时,此正则表达式返回 false
。
Example, without #
String text = "some text and test word";
String matchingWord = "test";
boolean contains = text.matches(".*\\b" + matchingWord + "\\b.*");
// now contains == true;
But with hashtag `contains` was false. Example:
text = "some text and #test word";
matchingWord = "#test";
contains = text.matches(".*\\b" + matchingWord + "\\b.*");
//contains == fasle; but I expect true
最佳答案
\b#
模式匹配 #
前面有单词字符:字母、数字或下划线。
如果需要匹配#
如果前面没有单词 char,请使用负向后视 (?<!\w)
.同样,要确保尾随 \b
如果存在非单词字符则匹配,使用 (?!\w)
负前瞻:
text.matches("(?s).*(?<!\\w)" + matchingWord + "(?!\\w).*");
使用 Pattern.quote(matchingWord)
如果你的 matchingWord
是个好主意可以包含特殊的正则表达式元字符。
或者,如果您打算匹配空格或字符串开头/结尾之间的搜索词,您可以使用 (?<!\S)
作为初始边界和(?!\S)
作为尾随的
text.matches("(?s).*(?<!\\S)" + matchingWord + "(?!\\S).*");
还有一件事:.*
在.matches
不是最好的正则表达式解决方案。像 "(?<!\\S)" + matchingWord + "(?!\\S)"
这样的正则表达式与 Matcher#find()
将以更优化的方式处理,但您需要初始化 Matcher
对象。
关于java - 在正则表达式中匹配带有井号 (#) 的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41396917/