Wildcard character

The wildcard character is the . (dot) and it matches any character. Thus, a pattern that consists of "." will match these (and other) input sequences: "A", "a", "x", and so on.

Quantifier

A quantifier determines how many times an expression is matched.

The quantifiers are shown here:

SymbolMeaning
+Match one or more.
*Match zero or more.
?Match zero or one.

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

A match with a literal pattern:


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

public class Main {
  public static void main(String args[]) {
    Pattern pat = Pattern.compile("Java");
    Matcher mat = pat.matcher("Java");
    boolean found = mat.matches(); // check for a match
    System.out.println(found);

    mat = pat.matcher("Java SE 6"); // create a new matcher
    found = mat.matches(); // check for a match
    System.out.println(found);
  }
}

You can use find( ) to determine if the input sequence contains a subsequence that matches the pattern.


// Use find() to find a subsequence. 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String args[]) {
    Pattern pat = Pattern.compile("Java");
    Matcher mat = pat.matcher("Java SE 6");
    System.out.println(mat.find());
  }
}

Use find() to find multiple subsequences.

The following program finds two occurrences of the pattern "test":


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

public class Main {
  public static void main(String args[]) {
    Pattern pat = Pattern.compile("test");
    Matcher mat = pat.matcher("test 1 2 3 test");
    while (mat.find()) {
      System.out.println("test found at index " + mat.start());
    }
  }
}

Output:


test found at index 0
test found at index 11
Home 
  Java Book 
    Essential Classes  

Matcher:
  1. Regular Expression Processing
  2. Normal character
  3. Wildcard character
  4. Using Wildcards and Quantifiers
  5. Greedy behavior
  6. Working with Classes of Characters
  7. Using replaceAll( )
  8. Using split( )
  9. Matcher: appendReplacement(StringBuffer sb,String replacement)
  10. Matcher.appendTail(StringBuffer sb)
  11. Matcher: find()
  12. Matcher: group()
  13. Matcher: group(int group)
  14. Matcher: groupCount()
  15. Matcher: lookingAt()
  16. Matcher: matches()
  17. Matcher: replaceAll(String text)
  18. Matcher: start()