Tuesday, November 15, 2011

Regular expressions simplify pattern-matching code - 11


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:
  1. java RegexDemo a? abaa: uses a greedy quantifier to match a in abaa 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 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.
  1. java RegexDemo a* abaa: uses a greedy quantifier to match a in abaa 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 as.

1 comment:

Unknown said...

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