0% completed
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.
Method | Description |
---|---|
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. |
In this example, we use the Pattern.split()
method to split a comma-separated string into individual elements.
Explanation:
Pattern.compile(",")
.split()
method divides the input string "apple,banana,cherry,dates"
at each comma.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.
Explanation:
(?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.Pattern.matches()
compiles the regex and tests if the entire email string matches the pattern.Understanding these basic operations lays the foundation for more advanced text processing tasks using Java's regex API.
.....
.....
.....