[英]How can I extract the words from this string “ !!one!! **two** @@three@@” using Regex in Ruby
In IRB, I can do this: 在IRB中,我可以这样做:
c = /(\\b\\w+\\b)\\W*(\\b\\w+\\b)\\W*(\\b\\w+\\b)\\W*/.match(" !!one** * two * @@three@@ ") 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" => MatchData“一个** * 两个 * @@三个@@”1:“一个”2:“两个”3:“三个”
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. 但假设我事先不知道单词的数量,我怎样才能从字符串中提取所有单词“。例如,它可能是”!! ** ** * 2 * @@ three @@“例如,但在另一个例子中可能是“!! five ** * six *”。
Thanks. 谢谢。
> " !!one** *two* @@three@@ ".scan(/\w+/)
=> ["one", "two", "three"]
Also, scan
can return array of arrays in case of using ()
. 此外,在使用()
情况下, scan
可以返回数组数组。
> "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 http://ruby-doc.org/core/classes/String.html#M000812
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.