转换数组regex中的字符串

时间:2015-08-21 11:33:15

标签: ruby regex

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

我想使用正则表达式["1", "potato chips", 3.99]

将其转换为数组

我正在做这件事

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

但它给我的输出为

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

2 个答案:

答案 0 :(得分:2)

转换为数组:

/^\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

使用split(受@ndn启发):

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

答案 1 :(得分:0)

试试这个正则表达式:

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

Regex live here.

解释

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

希望它有所帮助。