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 matcha
inabaa
once or not at all. The following output results:
Regex = a?
Text = abaa
Found a
starting at index 0 and ending at index 1
Found
starting at index 1 and ending at index 1
Found a
starting at index 2 and ending at index 3
Found a
starting at index 3 and ending at index 4
Found
starting at index 4 and ending at index 4
The output reveals five matches. Although the first, third, and fourth matches come as no surprise in that they reveal the positions of the three
a
s 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 matcha
inabaa
zero or more times. The following output results:
Regex = a*
Text = abaa
Found a
starting at index 0 and ending at index 1
Found
starting at index 1 and ending at index 1
Found aa
starting at index 2 and ending at index 4
Found
starting at index 4 and ending at index 4
The 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 a
s.
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