rexular expression quantifiers

  • Thread starter Johnathan Smith
  • Start date
J

Johnathan Smith

hi there

just a quick question

what is the difference between greedy and non greedy quantifiers?

cheers
 
R

Robert Klemme

2008/1/7 said:
just a quick question

what is the difference between greedy and non greedy quantifiers?

The greediness.

Seriously: why don't you just try it out in IRB?

s=("a"*10 + "b")
s+=s
s.scan /\w+b/
s.scan /\w+?b/

Cheers

robert
 
M

Marcin Mielżyński

Robert Klemme pisze:
The greediness.

Seriously: why don't you just try it out in IRB?

s=("a"*10 + "b")
s+=s
s.scan /\w+b/
s.scan /\w+?b/

There's also possessive one (doesn't backtrack)
ruby 1.9 or jruby 1.1 (trunk)

irb(main):011:0> "aa" =~ /a++a/
=> nil


lopex
 
J

James Gray

Robert Klemme pisze:

There's also possessive one (doesn't backtrack)
ruby 1.9 or jruby 1.1 (trunk)

irb(main):011:0> "aa" =3D~ /a++a/
=3D> nil

You can get Ruby 1.8 to not backtrack as well:

$ ruby -ve 'p "aa" =3D~ /(?>a+)a/'
ruby 1.8.6 (2007-09-24 patchlevel 111) [i686-darwin9.1.0]
nil

James Edward Gray II=
 
G

Giles Bowkett

what is the difference between greedy and non greedy quantifiers?

I agree the best way to find out is to audition it in IRB, but just
for completeness, the difference is that a greedy quantifier will grab
the largest possible match, and the non-greedy quantifier will grab
the smallest possible match.

e.g.:
/<.+>/.match("<b>stuff</b>")[0]
=> said:
/<.+?>/.match("<b>stuff</b>")[0]
=> "<b>"

The only difference is +?, the non-greedy quantifier; using it, you
get the first possible match, instead of the biggest. QED.

--
Giles Bowkett

Podcast: http://hollywoodgrit.blogspot.com
Blog: http://gilesbowkett.blogspot.com
Portfolio: http://www.gilesgoatboy.org
Tumblelog: http://giles.tumblr.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top