转换数组regex中的字符串



我有字符串"1 potato chips at 3.99"

我想把它转换成数组使用正则表达式["1", "potato chips", 3.99]

当前我正在做这个

/^([ds./]+)s+(.*)s+([ds./]+)$/.match(input).to_a

但是它给我的输出是

[" 1 book at 12.99", " 1", "book at", "12.99"]

转换为数组:

/^s*(d+)s+(.*?)s+w+s+([0-9.]+)$/
       .match("1 potato chips at 3.99")
       .to_a.tap { |a| a.shift }
#⇒ [
#  [0] "1",
#  [1] "potato chips",
#  [2] "3.99"
#]

,或者更好的:

/^s*(d+)s+(.*?)s+w+s+([0-9.]+)$/
       .match("1 potato chips at 3.99").captures

using split(受@ndn启发):

"1 potato chips at 3.99".split(/(?<=d)s+| at |s+(?=d)/)

试试这个regex:

(?:d+.?)+|[^d]+

Regex live here.

解释:

(?:d+.?)+      # as many numbers and/or dots as possible
|[^d]+          # OR not numbers

希望能有所帮助。

最新更新