You can use regular expressions (regex) to perform pattern matching and manipulate strings. Regular expressions are powerful tools for tasks like string validation, searching, and extraction based on patterns.
To work with regular expressions in Java, you’ll typically use the java.util.regex package, which provides classes like Pattern and Matcher. A regular expression can be a single character, or a more complicated pattern.
To use regex in Java, you first need to create a Pattern object, which represents the regex pattern. You can do this using the Pattern.compile() method.
Example :-
import java.util.regex.Pattern;
Pattern pattern = Pattern.compile(“abc”); // Example pattern: matches “abc” in a string
You can use the Matcher class to match a regex pattern against a string.
Example :-
import java.util.regex.Matcher;
String text = “The abc is here.”;
Matcher matcher = pattern.matcher(text);
while (matcher.find())
{
System.out.println(“Found: ” + matcher.group());
}
In this example, the find() method is used to find the next occurrence of the pattern in the input string.
Here are some common regex patterns and their meanings:
Matcher class:-
The Matcher class is typically associated with programming languages and libraries that provide support for regex pattern matching. It’s not a universal class found in all programming languages, but it’s commonly used in languages like Java.
The Matcher class is part of the Java regular expressions package (java.util.regex) and is used to perform pattern matching operations with regular expressions.
S/No. | Method | Description |
---|---|---|
1 | boolean matches() | test whether the regular expression matches the pattern. |
2 | boolean find() | finds the next expression that matches the pattern. |
3 | boolean find(int start) | finds the next expression that matches the pattern from the given start number. |
4 | String group() | returns the matched subsequence. |
5 | int start() | returns the starting index of the matched subsequence. |
6 | int end() | returns the ending index of the matched subsequence. |
7 | int groupCount() | returns the total number of the matched subsequence. |
Pattern class :-
It is the compiled version of a regular expression. It is used to define a pattern for the regex engine.
S/No. | Method | Description |
---|---|---|
1 | static Pattern compile(String regex) | compiles the given regex and returns the instance of the Pattern. |
2 | Matcher matcher(CharSequence input) | creates a matcher that matches the given input with the pattern. |
3 | static boolean matches (String regex, CharSequence input) | It works as the combination of compile and matcher methods. It compiles the regular expression and matches the given input with the pattern. |
4 | String[] split(CharSequence input) | splits the given input string around matches of given pattern. |
5 | String pattern() | returns the regex pattern. |