Java Reference
In-Depth Information
The end() method returns the index of the last character in the matched string plus one. Therefore, after a
successful invocation of the find() method, the difference between the values returned by the end() and start()
methods will give you the length of the matched string. Using the substring() method of the String class, you can
get the matched string as follows:
// Continued from previous fragment of code
if (m.find()) {
// str is the string we are looking into
String foundStr = str.substring(m.start(), m.end());
System.out.println("Found string is:" + foundStr);
}
The group() method returns the found string by the previous successful find() method call. Recall that you can
also get the previous matched string using the substring() method of the String class by using the start and end of
the match. Therefore, the above snippet of code can be replaced by the following code:
if (m.find()) {
String foundStr = m.group();
System.out.println("Found text is:" + foundStr);
}
Listing 14-2 illustrates the use of these methods. The validations for the method's arguments have been omitted
for clarity. The program attempts to find the "[abc]@." pattern in different strings.
Listing 14-2. Using Pattern and Matcher Classes
// PatternMatcher.java
package com.jdojo.regex;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class PatternMatcher {
public static void main(String[] args) {
String regex = "[abc]@.";
String source = "cric@jdojo.com is a valid email address";
PatternMatcher.findPattern(regex, source);
source = "kelly@jdojo.com is invalid";
PatternMatcher.findPattern(regex, source);
source = "a@band@yea@u";
PatternMatcher.findPattern(regex, source);
source = "There is an @ sign here";
PatternMatcher.findPattern(regex, source);
}
 
Search WWH ::




Custom Search