java.util.regex.Pattern

java.util.regex.Pattern is a class in Java used to represent a compiled regular expression. It converts a regular expression into a pattern that can be used for matching and searching text. Pattern is commonly used together with the Matcher class for regex operations. It is useful for validation, searching, splitting, and identifying text patterns.

Important Features:

  • Creates compiled regular-expression patterns.
  • Supports matching and searching operations.
  • Works with the Matcher class.
  • Supports regex flags such as case-insensitive matching.
  • Can split strings using regular expressions.
  • Detects invalid regular-expression syntax.
Syntax:
Pattern pattern = Pattern.compile("regular_expression");
Matcher matcher = pattern.matcher("input");Code language: JavaScript (javascript)
Example to check whether a string contains only digits:
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher("12345");

System.out.println(matcher.matches());Code language: JavaScript (javascript)
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class PatternDemo {
    public static void main(String[] args) {

        Pattern pattern = Pattern.compile("[0-9]+");

        String input = "12345";

        Matcher matcher = pattern.matcher(input);

        if (matcher.matches()) {
            System.out.println("Input contains only digits.");
        } else {
            System.out.println("Input does not contain only digits.");
        }
    }
}
Output:
Input contains only digits.

Methods of Pattern

Method Signature and Short Description

public static Pattern compile(String regex)

Compiles the given regular expression into a Pattern object.

public static boolean matches(String regex, CharSequence input)

Compiles the regular expression and attempts to match the complete input sequence.

public String[] split(CharSequence input)

Splits the given input string around matches of the pattern.

public static String quote(String s)

Returns a literal pattern for the specified string.

public Matcher matcher(CharSequence input)

Creates a Matcher object for matching the pattern against the specified input.

public String pattern()

Returns the regular-expression string from which the pattern was compiled.

public int flags()

Returns the match flags used when compiling the pattern.

public final class Matcher

Class used with Pattern to perform regular-expression matching operations.

public class PatternSyntaxException extends IllegalArgumentException

Exception thrown when a regular expression contains invalid syntax.

Scroll to Top