Trusted answers to developer questions

What is a regex.Pattern class in Java?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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.

Code

// 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*",
"Ahhhhhhhhh"));
// 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).

RELATED TAGS

java
pattern class
regex.pattern
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?