Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex whole word [duplicate]

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

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"

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

like image 771
Kris B Avatar asked Dec 05 '22 20:12

Kris B


1 Answers

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:

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

e.g.,

  String text = "the quick brown fox jumps over the lazy dog";
  System.out.println(text.matches(regex));
like image 103
Hovercraft Full Of Eels Avatar answered Dec 14 '22 23:12

Hovercraft Full Of Eels