Wednesday, November 16, 2011

Regular expressions simplify pattern-matching code - 12

 java RegexDemo a+ abaa: uses a greedy quantifier to match a in abaa one or more times. The following output results:
Regex = a+
Text = abaa
Found a
  starting at index 0 and ending at index 1
Found aa
  starting at index 2 and ending at index 4

The output reveals two matches. Unlike a? and a*, a+ does not match the absence of a. Thus, no zero-length matches result. Like a*, a+ matches all consecutive as.
  1. java RegexDemo a{2} aababbaaaab: uses a greedy quantifier to match every aa sequence in aababbaaaab. The following output results:
Regex = a{2}
Text = aababbaaaab
Found aa
  starting at index 0 and ending at index 2
Found aa
  starting at index 6 and ending at index 8
Found aa
  starting at index 8 and ending at index 10
  1. java RegexDemo a{2,} aababbaaaab: uses a greedy quantifier to match two or more consecutive as in aababbaaaab. The following output results:
Regex = a{2,}
Text = aababbaaaab
Found aa
  starting at index 0 and ending at index 2
Found aaaa
  starting at index 6 and ending at index 10
  1. java RegexDemo a{1,3} aababbaaaab: uses a greedy quantifier to match every a, aa, or aaa in aababbaaaab. The following output results:
Regex = a{1,3}
Text = aababbaaaab
Found aa
  starting at index 0 and ending at index 2
Found a
  starting at index 3 and ending at index 4
Found aaa
  starting at index 6 and ending at index 9
Found a
  starting at index 9 and ending at index 10
  1. java RegexDemo a+? abaa: uses a reluctant quantifier to match a in abaa one or more times. The following output results:
Regex = a+?
Text = abaa
Found a
  starting at index 0 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

Unlike its greedy variant in the third example, the reluctant example produces three matches of a single a because the reluctant quantifier tries to find the shortest match.

No comments: