The operations that can use regular expressions on String actually make use of the functions of java.util.regex.Pattern and java.util.regex.Matcher. When calling String's matches() method, it actually calls Pattern's static method matches(). This method returns a boolean value indicating whether the string matches the regular expression.
If you want to treat the regular expression as an object for reuse, you can use Pattern's static method compile() to compile it. The compile() method will return a Pattern instance, which represents a regular expression. You can then reuse the matcher() method of the Pattern instance to return a Matcher instance, which represents an instance that matches the regular expression. There are some searches on this instance. Methods that meet regular expression conditions are available for operation. Example 6.11 demonstrates this.
** Example 6.11UsePatternMatcher.java
import java.util.regex.*;
public class UsePatternMatcher {
public static void main(String[] args) {
String phones1 =
"Justin's mobile number: 0939-100391n" +
"momor's mobile phone number: 0939-666888n";
Pattern pattern = Pattern.compile(".*0939-\d{6}");
Matcher matcher = pattern.matcher(phones1);
while(matcher.find()) {
System.out.println(matcher.group());
}
String phones2 =
"caterpillar's mobile phone number: 0952-600391n" +
"bush's mobile phone number: 0939-550391";
matcher = pattern.matcher(phones2);
while(matcher.find()) {
System.out.println(matcher.group());
}
}
}
Example 6.11 will search for numbers starting with 0939. Assuming that the numbers come from more than one source (such as phones1, phones2), you can compile the regular expression and return a Pattern object. You can then reuse this Pattern object during comparison. Use matcher() to return matching Matcher instances. The find() method indicates whether there is a matching string, and the group() method can return the matching string. The execution results of the program are as follows:
Justin’s mobile number: 0939-100391
momor’s mobile phone number: 0939-666888
bush’s mobile phone number: 0939-550391
Let's rewrite Example 6.9 using Pattern and Matcher so that the program can return strings that match the regular expression instead of returning strings that don't match.
** Example 6.12RegularExpressionDemo2.java
import java.util.regex.*;
public class RegularExpressionDemo2 {
public static void main(String[] args) {
String text = "abcdebcadxbc";
Pattern pattern = Pattern.compile(".bc");
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
System.out.println(matcher.group());
}
System.out.println();
}
}
style='font-family:宋体'>Execution results:
abc
ebc
xbc
This article comes from the CSDN blog. Please indicate the source when reprinting: http://blog.csdn.net/wofe912/archive/2009/12/18/5030571.aspx