java 正则表达式全字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7459263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:03:41  来源:igfitidea点击:

Regex whole word

javaandroidregex

提问by Kris B

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.

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

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".

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

I've tried this:

我试过这个:

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

I've also tried:

我也试过:

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

I've also tried this regex: "\bthe\b"

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

And they always return false. I feel like I'm missing something pretty obvious here, since this shouldn't be too difficult. :)

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

回答by Hovercraft Full Of Eels

If you use matches, it must match the whole String. String#contains(...)may be what you're looking for, or perhaps you want to put some wild cards before and after your word:

如果使用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));

回答by Hari Menon

Try this regex:

试试这个正则表达式:

".*\bthe\b.*"

Basically, what you are trying to match it against is the string "the", but you need to return a match even if the input has other things, so you need to put ".*" on both sides for that.

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

回答by zneak

Bzzt! It will naturally return truefor the second sentence, since the word theappears two times: Thequick brown fox jumps over thelazy dog". Your second sentence still has the second the.

呸!它会自然恢复true的第二句话,因为这个词the出现两次:敏捷的棕色狐狸跳过懒狗”你的第二句话仍然有第二个。

Your regex is correct. However, you'll need to use the Pattern.find?method instead of matches, because matchesattempts to match against the whole string. Pattern.find, on the other hand, will locate substrings that match your pattern.

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