Java Regular Expression


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:

  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  4. public class Demo
  5. {
  6. public static void main( String[] args){
  8. // String to be scanned to find the pattern.
  9. String line = "This order was placed for QT3000! OK?";
  10. String pattern = "(.*)(\\d+)(.*)";
  12. // Create a Pattern object
  13. Pattern r = Pattern.compile(pattern);
  15. // Now create matcher object.
  16. Matcher m = r.matcher(line);
  17. if (m.find( )) {
  18. System.out.println("Found value: " + );
  19. System.out.println("Found value: " + );
  20. System.out.println("Found value: " + );
  21. } else {
  22. System.out.println("NO MATCH");
  23. }
  24. }
  25. }

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


Please enter your comment!
Please enter your name here