Regular Expression in Java
In Java, a regular expression is a sequence of characters that defines a search pattern. Regular expressions are used to perform pattern matching and string manipulation operations on text. The Java language has built-in support for regular expressions through the java.util.regex package, which contains the classes and methods needed to work with regular expressions in Java.
The main class for working with regular expressions in Java is the Pattern class, which represents a compiled regular expression. To use a regular expression in a Java program, you first create a Pattern object by calling the static compile() method and passing in the regular expression as a string. Once you have a Pattern object, you can use it to create a Matcher object, which is used to perform matching operations on a string.
For example, the following code creates a Pattern object for a regular expression that matches a date in the format "dd/mm/yyyy":
import java.util.regex.*;
Pattern datePattern = Pattern.compile("\\d{2}/\\d{2}/\\d{4}");You can use the Matcher class to check if a string matches the regular expression, and to extract specific parts of the string that match the regular expression. For example, the following code uses a Matcher to check if a string is a valid date in the format "dd/mm/yyyy":
Matcher dateMatcher = datePattern.matcher("22/12/2022");
if (dateMatcher.matches()) {
System.out.println("Valid date");
} else {
System.out.println("Invalid date");
}Regular expressions in Java are powerful and flexible, but can also be complex and difficult to understand. It's important to have a good understanding of regular expression syntax and concepts when working with them in Java.
Examples:
//Example for Email Validation:
String REGEX = "[a-zA-Z_0-9]*_[a-zA-Z_0-9]*[@][a-z]{4,7}.com";
String INPUT = "maasH34d_dha@uyhiupl.com";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
int count = 0;
System.out.println(INPUT.matches(REGEX));
Output:
true
Example 2:
String REGEX = "\\bcat\\b";
String INPUT = "cat cat cat l65dfcat";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
while(m.find()) {
System.out.println("Pattern found from " + m.start() +" to "+m.end());
}
}
Output:
Pattern found from 0 to 3
Pattern found from 4 to 7
Pattern found from 8 to 11
Reference 1: https://www.javatpoint.com/java-regex
Reference 2: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
Reference 3: https://www.geeksforgeeks.org/regular-expressions-in-java/