正则表达全字 [英] Regex whole word
问题描述
我觉得这个问题有点傻,但是从我读过的所有内容来看,这应该有效,对我来说不行。我只是想用正则表达式匹配字符串中的整个单词。
I feel a little silly asking this question, but from everything I've read, this should work and it doesn't, for me. I'm just trying to match a whole word in a string using regular expressions.
所以,如果我试图在一个句子中找到the这个词,它应该返回true,因为快速的棕色狐狸跳过懒狗,但是因为快速的棕色狐狸跳过懒狗而返回false。
So, if I'm trying to find the word "the" in a sentence, it should return true for "the quick brown fox jumps over the lazy dog", but return false for "there quick brown fox jumps over the lazy dog".
我试过这个:
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
I've also tried this regex: "\bthe\b"
他们总是返回假。我觉得我在这里遗漏了一些非常明显的东西,因为这不应该太难。 :)
And they always return false. I feel like I'm missing something pretty obvious here, since this shouldn't be too difficult. :)
推荐答案
你需要的是matcher.find()
What you need is matcher.find()
http: //download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Matcher.html#find%28%29
这篇关于正则表达全字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!