Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pattern class

What is a regex.Pattern class in Java?

Educative Answers Team

A regular expression is a defined pattern used for matching and manipulating strings. In Java, there is a built-in API for regular expressions:

java.util.regex package

This package has three classes:

  1. Pattern class
  2. Matcher class
  3. PatternSyntax Exception class

A regular expression is not the property of one particular programming language; instead, it is supported by multiple languages.

svg viewer

Pattern class

The util.regex.Pattern is used for defining text patterns. Some commonly used methods are:

Methods Description
compile (String regex, int flags) It compiles the given expression into a pattern using the given flags. Flags are optional.
flags() It returns the flags of the given expression.
matcher(charSequence input) It creates the matcher that matches the input with the given expression.
matches(String regex, CharSequence input) It compiles the regular expression and matches it against the input.
pattern() It returns the regular expression from which the pattern is derived.
split(CharSequence input) It splits the given pattern around the matches of the given input.
toString() It returns the String of the given pattern.


// Pattern.matches() in Java 
import java.util.regex.Pattern; 
class Main 
    public static void main(String args[]) 
        // The following statement prints true because
        // "Ah*" matches "Ahhhhhhhh"
        System.out.println (Pattern.matches("Ah*", 
        // The following statement prints false because
        // "Educative" matches "Educative Inc."
        System.out.println (Pattern.matches("Educative", 
                                            "Educative Inc")); 

In the above code, the “*” symbol means that the character before it can repeat finitely at that position (e.g., hel*o is equivalent to hello).


pattern class
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring