我觉得问这个问题有点傻,但从我读过的所有内容来看,这对我来说应该有效,但事实并非如此。我只是想使用正则表达式来匹配字符串中的整个单词。
所以,如果我试图在句子中找到“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。我觉得我在这里遗漏了一些非常明显的东西,因为这应该不会太困难。 :)
如果你使用matches
,它必须匹配整个字符串。String#contains(...)
可能是您正在寻找的内容,或者您可能想在单词前后添加一些通配符:
String regex = ".*\\bthe\\b.*";
e.g.,
String text = "the quick brown fox jumps over the lazy dog";
System.out.println(text.matches(regex));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)