describe the method:
find->
Attempts to find the next subsequence of the input sequence that matches the pattern.
This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.
If the match succeeds then more information can be obtained via the start, end, and group methods.
Returns:
true if, and only if, a subsequence of the input sequence matches this matcher's pattern
start->The index of the first character matched
end->The offset after the last character matched
group->
Returns the input subsequence captured by the given group during the previous match operation.
For a matcher m, input sequence s, and group index g, the expressions m.group(g) and s.substring(m.start(g), m.end(g)) are equivalent.
Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group().
If the match was successful but the group specified failed to match any part of the input sequence, then null is returned. Note that some groups, for example (a*), match the empty string. This method will return the empty string when such a group successfully matches the empty string in the input.
之前的写法是:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestPattern {
public static void main(String[] args) {
Pattern p=Pattern.compile("_(\\d+)");
Matcher m=p.matcher("a_3_4");
System.out.println(m.find());
System.out.println(m.start());
System.out.println(m.end());
System.out.println(m.group(1));
}
}
输出结果:
true
1
3
3
但我想取出那个‘4’,所以用到了‘$'这个符号:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestPattern {
public static void main(String[] args) {
Pattern p=Pattern.compile("_(\\d+)$");
Matcher m=p.matcher("a_3_4");
System.out.println(m.find());
System.out.println(m.start());
System.out.println(m.end());
System.out.println(m.group(1));
}
}
运行结果:
true
3
5
4