learningjava
learningjava

Reputation: 49

How do you use regex on a word that cannot contain a number in java?

Basically, I want to use regular expressions to return false if the string contains "word" AND is followed by a number, i.e. returning false if "theword1", "theword2", "theword5" etc.

However, I still want it to return true if it is just "theword" without a number or a completely different string like "apple5" - the word and number have to be together to return false. I know it can be done but I really am stuck.

Here is what I've tried so far (doesn't work):

str.matches(".*([word][^1-9])*.*")

My logic was 0 or more characters (.*) word NOT next to a number occurring 0 or more times (([word][^1-9])*) and then 0 or more characters afterwards.

Upvotes: 3

Views: 458

Answers (2)

Bohemian
Bohemian

Reputation: 424993

Match on “word” when not followed by a digit implement as a negative look ahead:

boolean hasUnnumberedWord(String str, String word) {
    return str.matches(".*" + word + "(?!\\d).*");
}

If “word” could contain characters that had special meaning in regex, use Pattern.quote(word) instead or word.

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163257

The pattern [word][^1-9] that you tried consists of 2 character classes. It will first match a single character, one of w o r d followed by a single character other than a digit 1-9

You can exclude the match by asserting not word followed by a digit in the string.

^(?!.*word\d).+

Regex demo

Upvotes: 2

Related Questions