1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Zero or More: * and *?

By

The preceding element will be matched zero or more times. The non-greedy version will match only enough to satisfy the regular expression. This may mean it matches nothing at all (matching nothing will satisfy the * quantifier). This quantifier is mostly used "sandwiched" between two other elements. If no elements follow the non-greedy version of this quantifier, it will match zero characters.

#!/usr/bin/env ruby

text = "! foo ! bar ! baz !"

# The greedy version will match the
# whole <a href="/od/glossary/g/string.htm">string</a> and produce "X"
puts text.sub( /!.*!/, "X" )

# The non-greedy version will match
# the minimum in order to match the
# requirements, and produce the string
# "X bar ! baz !", removing only the
# first section
puts text.sub( /!.*?!/, "X" )
  1. About.com
  2. Technology
  3. Ruby
  4. Regular Expressions
  5. Zero or More: * and *?

©2014 About.com. All rights reserved.