Home » Core Java » util » regex » String.matches method example

About Ilias Tsagklis

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

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");
    }
  }
}

Output:

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

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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments