How can I extract the words from this string " !!one!! **two** @@three@@" using Regex in Ruby
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 nu开发者_运维问答mber 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.
> " !!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
精彩评论