Java Intermediate

0% completed

Previous
Next
Pattern Class in Java

The Pattern class is part of the java.util.regex package and is used to compile regular expressions into pattern objects. These objects provide a reusable and efficient way to perform text matching and manipulation. The Pattern class offers several key methods for working with regular expressions, such as compiling regex with optional flags and splitting strings based on a pattern. In this lesson, we'll review the core methods of the Pattern class and see two simple examples demonstrating its usage without explicitly using the Matcher class.

Key Methods of the Pattern Class

MethodDescription
static Pattern compile(String regex)Compiles the given regular expression into a pattern.
static Pattern compile(String regex, int flags)Compiles the given regular expression with the specified flags (e.g., Pattern.CASE_INSENSITIVE).
Matcher matcher(CharSequence input)Creates a matcher that will match the given input against this pattern. (Not used directly here.)
String[] split(CharSequence input)Splits the input sequence around matches of the pattern.
static boolean matches(String regex, CharSequence input)A convenience method that compiles the regex and matches the input against it.

Examples

Example 1: Splitting a String Using Pattern.split()

In this example, we use the Pattern.split() method to split a comma-separated string into individual elements.

Java
Java

. . . .

Explanation:

  • We compile a regex pattern that matches a comma using Pattern.compile(",").
  • The split() method divides the input string "apple,banana,cherry,dates" at each comma.
  • The resulting array is iterated, and each element (fruit) is printed.

Example 2: Validating an Email Address Using Pattern.matches() with Flags

This example demonstrates how to validate an email address using a regex with an inline flag for case-insensitive matching. We use the static Pattern.matches() method to perform the validation without explicitly using the Matcher class.

Java
Java

. . . .

Explanation:

  • The regex (?i)^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$ is used to validate an email address:
    • (?i) is an inline flag that makes the pattern case-insensitive.
    • ^[A-Za-z0-9+_.-]+ matches one or more allowed characters in the local part.
    • @ matches the literal "@" symbol.
    • [A-Za-z0-9.-]+$ matches one or more allowed characters in the domain.
  • The static method Pattern.matches() compiles the regex and tests if the entire email string matches the pattern.
  • The output indicates whether the email is valid.

Understanding these basic operations lays the foundation for more advanced text processing tasks using Java's regex API.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next