O'Reilly logo

Learning Rails: Live Edition by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Greed

There’s one last feature of the repetition operators that can cause unexpected results: by default, they’re greedy. This isn’t a question of computing virtue, but rather one of how much content a regular expression can match at one go. This is a common issue in things like HTML, where you might see something like:

<a href= "http://example.com" >Example.com</a>

You might think you could match the HTML tags simply with an expression like:

/<.*>/

But instead of matching the opening tag and closing tag separately, that expression will grab everything from the opening < to the closing > of </a>, because it can. If you want to restrain a given expression so that it takes the smallest possible matching bite, add a ? behind any of the repetition operators:

/<.*?>/

Greed matters more when you use regular expressions to extract content from long strings, but it can yield confusing results even in supposedly simple matching. If you have mysterious problems, greed is a good thing to check for.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required