regex
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 formstr.matches(regex)
yields exactly the same result as the exressionjava.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.