Using RegEx in String Contains Method in Java

Using Regex in String contains method in Java example shows does the contains method support regex and the alternative ways of using the regex pattern inside contains.

Does the String contains method support a regex pattern?

No. The String contains method does not support a regex pattern. We cannot specify the regex pattern inside the String contains method.

Are there any alternatives so that we can use the regex to check if the string contains the specified substring? Yes, absolutely. We can either use the matches method of the String class or we can use the Pattern and Matcher classes to do the same.

The matches method returns true if the regex pattern matches with the string content. The below example shows how to check if a string contains any number using the matches method.

Output

Please note that the matches method matches the whole content of the string against the specified regex pattern. That is the reason I have specified “.*” at the beginning and at the end of the regex pattern.

We can also have multiple checks just like the contains method.

Output

The above-given code checks if the string contains any number and also contains substring “files”. Now let’s consider another example.

Output

Just like the String contains method, our code also matched “apple” with “pineapple”. But the good thing is since we are now using the matches method, we can match with the whole word only if we want to.

Output

I’ve used the word boundary “\b” to match with the whole word only in the second matches method.

Instead of the matches method, we can also use the Pattern and Matcher classes as the replacement of the String contains method as given below.

Output

Unlike the matches method, the Matcher class does not match the regex pattern against the whole string. That is the reason we do not need to specify “.*” at the start and at the end of the regex pattern. We can also write this code in one line as given below.

Output

However, please note that the pattern compilation is a costly operation. You should reuse the compiled pattern object if multiple checks with the same pattern are needed.

If you want to learn more about regular expression, please visit the Java Regex tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *