Regular expression: not all matches are printed when using System.out.println (m.matches ());

I am executing 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 the code is executed using System.out.println (m.matches ()); printed matches: BIP1234E and BIP5555E . but when System.out.println (m.matches ()) is removed from the code, matche BIP1111E is also printed.

Can someone explain how this is possible? Thnx a lot for your help.

+4
source share
2 answers

Matches in Java supports the index of found groups on a given line.

For example, the line shown in your example is BIP1111EgjgjgjhgjhgjgjgjgjhgjBIP1234EfghfhfghfghfghBIP5555E

There are 3 groups matching the pattern.

BIP1111E BIP1234E BIP5555E

When creating a template, it starts at index 0. When we iterate using m.find (), every time it finds a template, it marks the index position of the found template.

For example, the first gourp is at the beginning of a line, that is, it starts at 0 and continues to the 7th (0-based index) character of the line. The next time we say find (), it starts with the 8th character to find the next pattern match.

m.matches tries to match the entire string, and also manipulates the internal index.

when you call m.matches () before iterating using m.find (), the index moves from the initial 0. therefore, the first group of BIP1111E is skipped if you call m.matches ()

+1
source

You can use the Matcher.reset method to reset the pairing to its original state after calling matches . This method changes the current state of the pairing object, and the next time call find it starts looking for the first character g .

0
source

All Articles