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. :)
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With