String#scan puzzlement

M

Martin DeMello

I'm trying to match sequences of capitalised words - can someone
explain why the second regexp works but not the first?

irb(main):001:0> a = "And then we Went to The Next Place to be"
=> "And then we Went to The Next Place to be"
irb(main):002:0> a.scan /([A-Z]\w+\s+)+/
=> [["And "], ["Went "], ["Place "]]
irb(main):003:0> a.scan /(?:[A-Z]\w+\s+)+/
=> ["And ", "Went ", "The Next Place "]

martin
 
C

Carlos

Martin said:
I'm trying to match sequences of capitalised words - can someone
explain why the second regexp works but not the first?

irb(main):001:0> a = "And then we Went to The Next Place to be"
=> "And then we Went to The Next Place to be"
irb(main):002:0> a.scan /([A-Z]\w+\s+)+/
=> [["And "], ["Went "], ["Place "]]
irb(main):003:0> a.scan /(?:[A-Z]\w+\s+)+/
=> ["And ", "Went ", "The Next Place "]

Because when you group, scan returns arrays with [$1, $2, $3...], etc.,
but in "to The Next Place to be" =~ /([A-Z]\w+\s+)+/ there is only $1.
Put the last "+" inside a group.
--
 
M

Martin DeMello

Martin said:
I'm trying to match sequences of capitalised words - can someone
explain why the second regexp works but not the first?

irb(main):001:0> a = "And then we Went to The Next Place to be"
=> "And then we Went to The Next Place to be"
irb(main):002:0> a.scan /([A-Z]\w+\s+)+/
=> [["And "], ["Went "], ["Place "]]
irb(main):003:0> a.scan /(?:[A-Z]\w+\s+)+/
=> ["And ", "Went ", "The Next Place "]

Because when you group, scan returns arrays with [$1, $2, $3...], etc.,
but in "to The Next Place to be" =~ /([A-Z]\w+\s+)+/ there is only $1.
Put the last "+" inside a group.

ah! that makes things a lot clearer, thanks.

martin
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top