【问题标题】:Regex whole word [duplicate]正则表达式整个单词[重复]
【发布时间】:2011-11-19 12:44:09
【问题描述】:

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

所以,如果我想在一个句子中找到单词“the”,它应该为“the quick brown fox jumps over the lazy dog”返回 true,但对于“there quick brown fox jumps over the lazy dog”返回 false懒狗”。

我试过了:

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

我也试过了:

    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();

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

而且它们总是返回 false。我觉得我在这里遗漏了一些非常明显的东西,因为这应该不会太难。 :)

【问题讨论】:

  • 感谢您的回答,尽管我现在觉得自己更愚蠢了。 :)

标签: java android regex


【解决方案1】:

如果你使用matches,它必须匹配整个字符串。 String#contains(...) 可能是您要查找的内容,或者您​​可能想在单词前后添加一些通配符:

String regex = ".*\\bthe\\b.*";

例如,

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

【讨论】:

    【解决方案2】:

    【讨论】:

    • 可能比我的答案更好:+1
    【解决方案3】:

    试试这个正则表达式:

    ".*\\bthe\\b.*"
    

    基本上,您尝试匹配的是字符串“the”,但即使输入有其他内容,您也需要返回匹配项,因此您需要在两侧放置“.*”。

    【讨论】:

      【解决方案4】:

      嘘!第二句话自然会返回true,因为the这个词出现了两次:The quick brown fox jumps over the lazy dog"。你的第二句话还有第二个

      您的正则表达式是正确的。但是,您需要使用 Pattern.find 方法而不是 matches,因为 matches 会尝试匹配整个字符串。另一方面,Pattern.find 将定位与您的模式匹配的子字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-06
        • 1970-01-01
        • 1970-01-01
        • 2010-11-15
        • 2021-12-30
        • 2012-01-06
        相关资源
        最近更新 更多