Java Regular Expression syntax

Introduction

A regular expression is comprised of

  • normal characters
  • character classes
  • wildcard characters
  • quantifiers

Normal characters

A normal character is matched as-is.

Characters such as newline and tab are specified using the standard escape sequences.

The escape sequences begin with a \.

For example, a newline is specified by \n.

A normal character is also called a literal.

Character classes

A character class is a set of characters.

A character class is specified by putting the characters in the class between brackets.

For example, the class [wxyz] matches w, x, y, or z.

To specify an inverted set, precede the characters with a ^.

For example, [^wxyz] matches any character except w, x, y, or z.

You can specify a range of characters using a hyphen.

For example, to specify a character class that will match the digits 1 through 9, use [1-9].

Wildcard characters

The wildcard character is the dot(.) and it matches any character.

Thus, a pattern that consists of "." will match these input sequences: "A", "a", "x", and so on.

Quantifiers

A quantifier determines how many times an expression is matched.

The quantifiers are shown here:

Quantifiers       Meaning
+     Match one or more. 
*     Match zero or more. 
?     Match zero or one. 

For example, the pattern "x+" will match "x", "xx", and "xxx", among others.

The following code looks for a match with a literal pattern:

// A simple pattern matching demo. 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String args[]) {
    Pattern pat;/*from  w  w w.  j a v  a  2 s  .c  om*/
    Matcher mat;
    boolean found;

    pat = Pattern.compile("Java");
    mat = pat.matcher("Java");

    found = mat.matches(); // check for a match

    System.out.println("Testing Java against Java.");
    if (found)
      System.out.println("Matches");
    else
      System.out.println("No Match");

    System.out.println();

    System.out.println("Java 8 demo from demo2s.com and some more Java 8 tutorial ");
    mat = pat.matcher("Java 8"); // create a new matcher

    found = mat.matches(); // check for a match

    if (found)
      System.out.println("Matches");
    else
      System.out.println("No Match");
  }
}



PreviousNext

Related