Ruby解析带有正则表达式的字符串

时间:2013-08-26 09:19:02

标签: ruby regex

如果我有这样的字符串:[3 Series] 315,如何解析它以使用Ruby中的regexp从中生成子串series =“3 series”和model =“315”?这是正确的方法:

"[3 Series] 315".split /[|\]\s/

系列可以是字符串,也可以只是数字

3 个答案:

答案 0 :(得分:6)

_, series, model = "[3 Series] 315".scan(/(\d+\s\w+|\d+)/)

_, series, model = "[3 Series] 315".split /\[|\]\s/

series
# => "3 Series"
model
# => "315"

答案 1 :(得分:4)

re = '\[(\w \w*)\] (\d*)'
str = "[3 Series] 315"
_, series, model = str.match(re).to_a
=> ["[3 Series] 315", "3 Series", "315"]

series
=> 3 Series

model
=> 315

答案 2 :(得分:3)

另一种方法

> result, series, model = /\[(.+)\] (.+)/.match(str).to_a.flatten

> series
# => "3 series"

> model
# => "315"