The following examples illustrate the behavior of the six fundamental quantifiers in the greedy category, and the behavior of a single fundamental quantifier in each of the reluctant and possessive categories. These examples also introduce the zero-length match concept:
- java RegexDemo a? abaa
:uses a greedy quantifier to matchainabaaonce or not at all. The following output results:
Regex = a?
Text = abaa
Found a
starting at index 0 and ending at index 1Found
starting at index 1 and ending at index 1Found a
starting at index 2 and ending at index 3Found a
starting at index 3 and ending at index 4Found
starting at index 4 and ending at index 4The output reveals five matches. Although the first, third, and fourth matches come as no surprise in that they reveal the positions of the three
as in abaa, the second and fifth matches are probably surprising. Those matches seem to indicate that a matches b and also the text's end. However, that is not the case. a? does not look for b or the text's end. Instead, it looks for either the presence or lack of a. When a? fails to find a, it reports that fact as a zero-length match, a match of zero length where the start and end indexes are the same. Zero-length matches occur in empty text, after the last text character, or between any two text characters. - java RegexDemo a* abaa
:uses a greedy quantifier to matchainabaazero or more times. The following output results:
Regex = a*
Text = abaa
Found a
starting at index 0 and ending at index 1Found
starting at index 1 and ending at index 1Found aa
starting at index 2 and ending at index 4Found
starting at index 4 and ending at index 4The output reveals four matches. As with
a?, a* produces zero-length matches. The third match, where a* matches aa, is interesting. Unlike a?, a* matches either no a or all consecutive as.
1 comment:
Good examples!There is a lot of very useful knowledge in your post to help me solve problems.I enjoy reading your article and hope to see more.
Labels: java barcode expressions pattern-matching code
Post a Comment