Skip to content
Advertisement

How to find if a word immediately followed by a non-letter character exists in a String

I believe the most efficient solution to this issue is to use Regex but I’m uncertain of the syntax. When looking through a sentence, how do you identify if a word followed by a non-letter character (anything other than a,b,c,d,e…) is present in a string. Example below:

String word = "eat"

String sentence = "I like to eat!"
This satisfies the condition because the exclamation point is not a letter

String sentence = "I like to beat!"
This does not satisfy the condition because beat is not eat. This is also an application where the contains() method fails

String sentence = "I like to eats"
This does not satisfy the condition because eat is followed by a letter

Advertisement

Answer

Use the word boundary regex b, which matches between a letter and a non-letter (or visa versa):

str.matches(".*\b" + word + "\b.*")

See live demo.

Although numbers are also considered “word characters”, this should work for you.

I’ve used a word boundary are the start too so “I want to beat” does not match.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement