简体   繁体   中英

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

> " !!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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM