1. Computing

A Specific Number or Range: {n,m}, {n} and {n,m}?

By

The preceding element will be matched a specific number of times. In the case of the {n,m} forms, the preceding element will be matched between n and m times. In the case of the {n} form, it will be matched exactly n times. The range variation has a non-greedy version, where only the elements required to reach the minimum of n elements will be matched. The specific quantity version does not have a non-greedy version. The {n}? quantifier wouldn't make any sense--it must match exactly n elements and is neither greedy nor non-greedy.

#!/usr/bin/env ruby

# There are 5 e's
text = "teeeee"

# In this case, the regex will
# always match all 5 e's. If there
# were more, it would match up to
# 7 e's.
puts text.sub( /te{3,7}/, "X" )

# In this case, the regext will
# stop at 3 e's, since that all
# it takes to satisfy the quantifier
# in the least greedy way.
puts text.sub( /te{3,7}?/, "X" )

# This will match exactly 4 of
# the e's.
puts text.sub( /te{4}/, "X" )

©2014 About.com. All rights reserved.