Java regular expressions match and find match locations
For example, if the matching position of the Methods matching the Regular Expression in java is unclear, a few examples are provided. As follows:
String ss="ooaaoo"; Pattern pt=Pattern.compile("(o+)"); Matcher mt=pt.matcher(ss); // mt.lookingAt(); // mt.matches(); while(mt.find()){ System.out.println(mt.group(1)+"|||"+mt.start()); }
This result will obviously match twice, one at 0 and one at 4.
See the following code.
String ss="ooaaoo"; Pattern pt=Pattern.compile("(o+)"); Matcher mt=pt.matcher(ss); mt.lookingAt(); // mt.matches(); while(mt.find()){ System.out.println(mt.group(1)+"|||"+mt.start()); }After we remove the annotation of one of the matches or lookingat methods, only one matching occurs, that is, at 4 locations.
Let's look at the following code:
String ss="aaooaaoo"; Pattern pt=Pattern.compile("(o+)"); Matcher mt=pt.matcher(ss); mt.lookingAt(); // mt.matches(); while(mt.find()){ System.out.println(mt.group(1)+"|||"+mt.start()); }Our input string ss has changed. The result of this program will be a secondary match, one at 2 and one at 4.
Therefore, the following conclusions can be drawn:
1. When the input string starting with ss does not match the regular expression, matches and lookingat do not affect the next matching position.
2. If a regular expression is matched at the beginning of the input string, after you call matches or lookingat, the next matching position will be removed after the string that matches the start.