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

The Four Quantifiers

Quantifiers Supported by Ruby's Regular Expression Engine


Quantifiers tell how many times an element should be matched. Below is a list of all quantifiers supported by the Ruby regular expression engine, how to use them and examples of their use. Though you can get by with the common quantifiers such as + or ?, there are a few more you should know about.

To understand how quantifiers work, you have to also understand the concept of greed. Regular expression engines can either be greedy or non-greedy. Ruby's engine is greedy unless you tell it to be non-greedy.

A greedy engine will find as many characters as possible to match the regular expression. For example, the regular expression /te+/ will match a t followed by one or more e's, and will find as many e's it can to satisfy this condition. The code "tee".gsub( /te+/, "X" ) will produce "X"; the regular expression engine was greedy and matched both e's.

A non-greedy engine will find the least number of characters as possible to match the regular expression. Using the previous example and the + quantifier's non-greedy cousin +?, the outcome is different. The code "tee".gsub( /te+?/, "X" ) will produce "Xe". Since the quantifier was a non-greedy quantifier, it matched as few characters as possible in order to satisfy the requirements of the quantifier. Since one e character was enough, it stopped there.

By convention, the non-greedy cousins of the greedy quantifiers are suffixed with a ? character. Keep in mind that all quantifiers are greedy unless the non-greedy versions are used.

  1. About.com
  2. Technology
  3. Ruby
  4. Regular Expressions
  5. The Four Quantifiers

©2014 About.com. All rights reserved.