Regular Expressions in Java
Last Updated :
21 Sep, 2023
In Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions in Java are provided under java.util.regex package. This consists of 3 classes and 1 interface. The java.util.regex package primarily consists of the following three classes as depicted below in tabular format as follows:
Regex Classes and Interfaces
Regex in Java provides 3 classes and 1 interface which are as follows:
- Pattern Class
- Matcher Class
- PatternSyntaxException Class
- MatchResult Interface
More understanding can be interpreted from the image provided below as follows:
1. |
Pattern Class |
Used for defining patterns |
2. |
Matcher Class |
Used for performing match operations on text using patterns |
3. |
PatternSyntaxException Class |
Used for indicating syntax error in a regular expression pattern |
4. |
MatchResult Interface |
Used for representing the result of a match operation |
Pattern Class
This class is a compilation of regular expressions that can be used to define various types of patterns, providing no public constructors. This can be created by invoking the compile() method which accepts a regular expression as the first argument, thus returning a pattern after execution.
Example: Pattern class
Java
import java.util.regex.Pattern;
class GFG {
public static void main(String args[])
{
System.out.println(Pattern.matches(
"geeksforge*ks" , "geeksforgeeks" ));
System.out.println(
Pattern.matches( "g*geeks*" , "geeksfor" ));
}
}
|
Matcher class
This object is used to perform match operations for an input string in Java, thus interpreting the previously explained patterns. This too defines no public constructors. This can be implemented by invoking a matcher() on any pattern object.
1. |
find() |
It is mainly used for searching multiple occurrences of the regular expressions in the text. |
2. |
find(int start) |
It is used for searching occurrences of the regular expressions in the text starting from the given index. |
3. |
start() |
It is used for getting the start index of a match that is being found using find() method. |
4. |
end() |
It is used for getting the end index of a match that is being found using find() method. It returns the index of the character next to the last matching character. |
5. |
groupCount() |
It is used to find the total number of the matched subsequence. |
6. |
group() |
It is used to find the matched subsequence. |
7. |
matches() |
It is used to test whether the regular expression matches the pattern. |
Note: T Pattern.matches() checks if the whole text matches with a pattern or not. Other methods (demonstrated below) are mainly used to find multiple occurrences of patterns in the text.
Let us do discuss a few sample programs as we did for the Pattern class. Here we will be discussing a few Java programs that demonstrate the workings of compile(), find(), start(), end(), and split() in order to get a better understanding of the Matcher class.
Example 1: Pattern Searching
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG {
public static void main(String args[])
{
Pattern pattern = Pattern.compile( "geeks" );
Matcher m = pattern.matcher( "geeksforgeeks.org" );
while (m.find())
System.out.println( "Pattern found from "
+ m.start() + " to "
+ (m.end() - 1 ));
}
}
|
Output
Pattern found from 0 to 4
Pattern found from 8 to 12
Regex Character classes
x,y or z |
Any characters other than x,y or z |
characters from range a to z or A to Z. |
Union of a to f and m to t. |
All the range of elements intersection between two ranges |
a to z union with except b and c |
a to z union with except range m to p |
Below is the implementation of the above topic:
Java
import java.io.*;
import java.util.regex.*;
class GFG {
public static void main(String[] args)
{
System.out.println(Pattern.matches( "[a-z]" , "g" ));
System.out.println(
Pattern.matches( "[a-zA-Z]" , "Gfg" ));
}
}
|
Regex Metacharacters
X appears once or not |
X appears once or more than once |
X appears zero or not once |
X appears n times |
X appears n times or more than n |
X appears greater than equal to n times and less than m times. |
Below is the implementation of Regex Metacharacters:
Java
import java.io.*;
import java.util.regex.*;
class GFG {
public static void main(String[] args)
{
System.out.println(Pattern.matches( "[b-z]?" , "a" ));
System.out.println(
Pattern.matches( "[a-zA-Z]+" , "GfgTestCase" ));
System.out.println(Pattern.matches( "[^a-z]?" , "g" ));
System.out.println(
Pattern.matches( "[geks]*" , "geeksgeeks" ));
}
}
|
Output
false
true
false
true
Java Regex Finder Example
Any character |
Any digits, [0-9] |
Any non-digit, [^0-9] |
Whitespace character, [\t\n\x0B\f\r] |
Non-whitespace character, [^\s] |
Word character, [a-zA-Z_0-9] |
Non-word character, [^\w] |
Word boundary |
Non -Word boundary |
Below is the implementation of the Java Regex Finder:
Java
import java.io.*;
import java.util.regex.*;
class GFG {
public static void main(String[] args)
{
System.out.println(Pattern.matches( "\\d+" , "1234" ));
System.out.println(Pattern.matches( "\\D+" , "1234" ));
System.out.println(Pattern.matches( "\\D+" , "Gfg" ));
System.out.println(Pattern.matches( "\\S+" , "gfg" ));
}
}
|
Output
true
false
true
true
Conclusion
Lastly, let us do discuss some of the important observations as retrieved from the above article
- We create a pattern object by calling Pattern.compile(), there is no constructor. compile() is a static method in the Pattern class.
- Like above, we create a Matcher object using matcher() on objects of the Pattern class.
- Pattern.matches() is also a static method that is used to check if a given text as a whole matches the pattern or not.
- find() is used to find multiple occurrences of patterns in the text.
- We can split a text based on a delimiter pattern using the split() method
FAQs in Java Regex
Q1. What are regular expressions in Java?
Ans:
Regular Expressions in java are used for string patterns that can be used for searching, manipulating, and editing a string in Java.
Q2. What is a simple example of regular expression in Java?
Ans:
A simple example of a regular expression in java is mentioned below:
Java
import java.io.*;
import java.util.regex.*;
class GFG {
public static void main(String[] args)
{
System.out.println(Pattern.matches( "[a-z]" , "g" ));
System.out.println(Pattern.matches( "\\D+" , "Gfg" ));
System.out.println(Pattern.matches( "\\S+" , "gfg" ));
}
}
|
Please Login to comment...