regex Ruby使用正则表达式解析字符串[已关闭]

qgelzfjb  于 2022-11-18  发布在  Ruby
关注(0)|答案(3)|浏览(146)

**已关闭。**此问题不符合Stack Overflow guidelines。当前不接受答案。

要求代码的问题必须证明对要解决的问题有最低限度的了解。包括尝试的解决方案、为什么不起作用以及expected结果。另请参阅:Stack Overflow question checklist
9年前关闭了。
Improve this question
如何解析[3 Series] 315以生成2个子字符串:series = "3 series"model = "315"在Ruby中使用regexp?我的以下代码给出了语法错误:

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

series可以是字符串或数字

2w2cym1i

2w2cym1i1#

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

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

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

velaa5lx2#

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
smdnsysy

smdnsysy3#

另一种方法

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

> series
# => "3 series"

> model
# => "315"

相关问题