Java – regular expressions: using system. Java out. Println (m.matches()) will not print all matches;

I execute the following code:

public static void test() {
 Pattern p = Pattern.compile("BIP[0-9]{4}E");

 Matcher m = p.matcher("BIP1111EgjgjgjhgjhgjgjgjgjhgjBIP1234EfghfhfghfghfghBIP5555E");
 System.out.println(m.matches());
 while(m.find()) {
  System.out.println(m.group());
 }

}

What I can't explain is when using system out. When println (m.matches()) executes code; The printing competition is bip1234e and bip555e But when system out. println(m.matches()); Match bip111e is deleted from the code and printed

Can someone explain that this is possible? Thnx has given you a lot of help

Solution

The matcher in Java maintains the index of the found group in a given string

For example, in the string provided in your example – bip111egjgjgjhgjhgjgjgjhgjbip1234efghfhfghfghfghbip555e

There are 3 groups matching the pattern

BIP1111E BIP1234E BIP5555E

When a matcher is created, it starts at index 0 When we use M. find () to iterate the matcher, it marks the index position of the found pattern every time it finds the pattern

For example, the first gourp is at the beginning of the string – that is, from 0 to the seventh (0-based index) character of the string Next time we say find (), it starts with the eighth character and finds the next match of the pattern

m. Matches attempts to match the entire string, and it also manipulates the internal index

When you call m.matches () before using m.find (), the index will move from the initial value 0. Therefore, if M. matches() is called, the first set of bip111e is skipped

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>