Regular Expressions Implementation in Java

Introduction

Regular Expressions in JAVA are a set of special characters that help you find or match strings or a set of strings in your program. The expressions have a specialized syntax created only for this purpose. To use regular expressions in your programs, you will have to import the java.util.regex package. Regular expressions for Java and Perl Programming are quite similar. The java.util.regex package essentially contains three classes: Pattern Class, Matcher Class, and the PatternSyntaxException class.

  • Pattern Class – A Pattern object is the compiled representation of a regular expression and it has no public constructors. If you want to create a pattern object, you will have to call the compile() method that will return a Pattern object.
  • Matcher Class – The Matcher class is where the execution and mapping of the regular expressions take place. This class takes an input class and tries to match it to one of the regular expression representations of strings. There are no public constructors in this class. If you want to create a Matcher object, you will have to invoke the matcher () method on a Pattern object.
  • Pattern SyntaxException – This class catches syntax errors in a regular expression pattern.

Example

The following example will use regular expressions to check and find a digit string from an alphanumeric string.

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

public class RegexMatches
{
public static void main( String args[] )
{
// The input string that will be scanned
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";

// Pattern Object
Pattern r = Pattern.compile(pattern);

// Creating a 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");
}
}
}

 

OUTPUT

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

Leave a comment

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