String.matches method example

With this example we shall show you how to use String.matches(String regex) API method to check if a given String matches a given regular expression. Checking if a String matches a regular expression implies that you should:

  • Create a new String pattern, that is a regular expression.
  • Use matches(String regex) API method of String to check if the String matches the regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the exression java.util.regex.Pattern.matches(regex, str). It returns true if, and only if, this string matches the given regular expression.
  • Print the result.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;

public class StringConvenience {
  public static void main(String[] argv) {

    String pattern = ".*Q[^u]\d+\..*";
    String line = "Order QT300. Now!";
    if (line.matches(pattern)) {

System.out.println(line + " matches "" + pattern + """);
    } else {

System.out.println("NO MATCH");


Order QT300. Now! matches ".*Q[^u]d+..*"

This was an example of how to String.matches(String regex) API method in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button