# String#scan puzzlement

**URL:** <https://www.ruby-forum.com/t/string-scan-puzzlement/98085>\
**Category:** Ruby\
**Created:** [July 12, 2006, 2:46pm UTC](https://www.ruby-forum.com/t/string-scan-puzzlement/98085 "2006-07-12T14:46:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [July 12, 2006, 2:46pm UTC](https://www.ruby-forum.com/t/string-scan-puzzlement/98085/1 "2006-07-12T14:46:39Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [July 12, 2006, 2:56pm UTC](https://www.ruby-forum.com/t/string-scan-puzzlement/98085/2 "2006-07-12T14:56:13Z")

</div>

Martin DeMello wrote:

> 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.

---

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [July 12, 2006, 3:02pm UTC](https://www.ruby-forum.com/t/string-scan-puzzlement/98085/3 "2006-07-12T15:02:40Z")

</div>

On 7/12/06, Carlos [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 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
