Using or ‘|’ in regex [duplicate]

It’s because you are trying to match against the entire string instead of the part to find. For example, this code will find that only a part of the string is conforming to the present regex:

Matcher m = Pattern.compile("he|be|de").matcher("he is ");
m.find(); //true

When you want to match an entire string and check if that string contains he|be|de use this regex .*(he|be|de).*

. means any symbol, * is previous symbol may be present zero or more times. Example:

"he is ".matches(".*(he|be|de).*"); //true

Leave a Comment