FinDev
FinDev

Reputation: 439

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

Upvotes: 1

Views: 75

Answers (2)

Bohemian
Bohemian

Reputation: 425003

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.

Upvotes: 3

jdaz
jdaz

Reputation: 6043

You can use:

sentence.matches(".*\\b" + word + "[^a-zA-Z\\s].*");

If you want "I like to eat" to also match, you can use:

sentence.matches(".*\\b" + word + "([^a-zA-Z\\s]|$).*");

Upvotes: 2

Related Questions