【发布时间】:2016-12-30 13:17:28
【问题描述】:
我有正则表达式来检查某些文本是否包含单词(忽略边界)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
【问题讨论】:
-
那么,你需要匹配什么作为词边界呢?字符串或空格的开头?通常,您可以使用
(?<!\\S)作为初始边界,在这种情况下使用(?!\\S)作为结尾边界(text.matches(".*(?<!\\S)" + matchingWord + "(?!\\S).*");)。 -
另一种确保搜索词不在单词字符内的常用解决方案是使用明确的单词边界:
text.matches(".*(?<!\\w)" + matchingWord + "(?!\\w).*") -
您可以简单地使用
text.contains("#test")结果将是true,如果您有一些特殊情况或多种情况,请使用regex -
@PavneetSingh:如果文本中有
#testing,那也会返回true。 -
@WiktorStribiżew 是的,没错,我打算在之前的评论中给 OP 一些建议