Java Regular Expression

0
135

Java provides the java.util.regex package for pattern matching with regular expressions.

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.

The java.util.regex package primarily consists of the following three classes:

Pattern Class: A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors. To create a pattern, you must first invoke one of its public static compile() methods, which will then return a Pattern object. These methods accept a regular expression as the first argument.

Matcher Class: A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher() method on a Pattern object.

PatternSyntaxException: A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.

Following example illustrates how to find a digit string from the given alphanumeric string:
[java]

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo
{
public static void main( String[] args){

// String to be scanned to find the pattern.
String line = “This order was placed for QT3000! OK?”;
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(“Found value: ” + m.group(0) );
System.out.println(“Found value: ” + m.group(1) );
System.out.println(“Found value: ” + m.group(2) );
} else {
System.out.println(“NO MATCH”);
}
}
}
[/java]

On execution of the above program we will get the below output:

Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0

Facebook Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.