1. Home
  2. Computing & Technology
  3. Ruby

The Four Quantifiers
Quantifiers Supported by Ruby's Regular Expression Engine

By , About.com Guide

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.

Explore Ruby
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Ruby
  4. Regular Expressions
  5. The Four Quantifiers

©2010 About.com, a part of The New York Times Company.

All rights reserved.