Hello!!
Regular Expression is part of the Automata, and also called rational expression. We use it for finding the match of the string like validating the Email address, Password etc. It uses some special sequence of the character for matching, replacing manipulating the string. It is a powerful tool for matching.
Example:
a|b*
denotes {ε, "a", "b", "bb", "bbb", …}
In Java, Regular expression called regex is used to search replace and manipulate the string. It is present in the java.util.regex
package. It contains three classes.
- Pattern
- Matcher
- PatternSyntaxException
Pattern:- A pattern is an object which represents the regular expression. We uses public static compile() method for creating the regular expression. We pass the argument to the compile() method. It return the regular expression object. It have no the public constructor.
Matcher:- Matcher is a engine object, use to matches the input string with the return value of the public static compile() method. It defines no public constructor. We can find the matcher object by using matcher() method on pattern object.
PatternSyntaxException:- It is used to indicate the syntax error in the regular expression. It is unchecked type exception.
Here is an example of Regular Expression.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
public static void main( String args[] ) {
// String to be scanned to find the pattern.
String line = "This order was placed for Qt25?";
String pattern = "(.*)(\\d+)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println( m.group(0) );
System.out.println( m.group(1) );
System.out.println( m.group(2) );
}else {
System.out.println("NO MATCH");
}
}
}
Output:-
This order was placed for Qt25
This order was placed for Qt2
5
0 Comment(s)