正则表达全字

Kri*_*s B 4 java regex android

我觉得有点傻问这个问题,但是从我读过的所有内容来看,这应该是有效的,而对我来说则不然.我只是想用正则表达式匹配字符串中的整个单词.

所以,如果我试图在一个句子中找到"the"这个词,它应该返回true,因为"快速的棕色狐狸跳过懒狗",但是"快速的棕色狐狸跳过懒狗"会返回false .

我试过这个:

 String text = "the quick brown fox jumps over the lazy dog";
 return text.matches("\\bthe\\b");
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

    String text = "the quick brown fox jumps over the lazy dog";
    String regex = "\\bthe\\b";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(text);

    return matcher.matches();
Run Code Online (Sandbox Code Playgroud)

我也试过这个正则表达式:"\ bthe\b"

他们总是回归虚假.我觉得我错过了一些非常明显的东西,因为这不应该太难.:)

Hov*_*els 6

如果使用matches,则必须匹配整个String.String#contains(...)可能是你正在寻找的,或者你想在你的词之前和之后放一些外卡:

String regex = ".*\\bthe\\b.*";
Run Code Online (Sandbox Code Playgroud)

例如,

  String text = "the quick brown fox jumps over the lazy dog";
  System.out.println(text.matches(regex));
Run Code Online (Sandbox Code Playgroud)