tags:

views:

52

answers:

2

In IRB, I can do this:
c = /(\b\w+\b)\W*(\b\w+\b)\W*(\b\w+\b)\W*/.match(" !!one** *two* @@three@@ ")

And get this:
=> MatchData "one** *two* @@three@@ " 1:"one" 2:"two" 3:"three"

But assuming I don't know the number of words in advance, how can I still extract all words out of the string". For example, it might be " !!one** *two* @@three@@ " in one instance, but might be " !!five** *six* " in another instance.

Thanks.

+3  A: 
> " !!one** *two* @@three@@ ".scan(/\w+/)
=> ["one", "two", "three"]

Also, scan can return array of arrays in case of using ().

> "Our fifty users left 500 posts this month.".scan(/([a-z]+|\d+)\s+(posts|users)/i)
=> [["fifty", "users"], ["500", "posts"]]

http://ruby-doc.org/core/classes/String.html#M000812

Nakilon
A: 

Thanks for the tip with the String#scan method. Can the same be done with regular expression. I'm trying to learn how to use regular expression as it can be applied to other languages.

Thanks for all the tips.

mnguyen1nc
You really want to make this a comment on his answer or on your question, rather than a new answer.
Paul Rubel
As far as i know, regexp can't have undefined number of matches.
Nakilon