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:
Symbol | Meaning |
---|---|
+ | 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
Java Book
Essential Classes
Matcher:
- Regular Expression Processing
- Normal character
- Wildcard character
- Using Wildcards and Quantifiers
- Greedy behavior
- Working with Classes of Characters
- Using replaceAll( )
- Using split( )
- Matcher: appendReplacement(StringBuffer sb,String replacement)
- Matcher.appendTail(StringBuffer sb)
- Matcher: find()
- Matcher: group()
- Matcher: group(int group)
- Matcher: groupCount()
- Matcher: lookingAt()
- Matcher: matches()
- Matcher: replaceAll(String text)
- Matcher: start()