我有一个格式为"8pm9pm8pm7pm-10pm"
的字符串列表,需要在"pm"
之后插入一个空格。我希望它返回类似的内容:
[8pm, 9pm, 8pm, 7pm-10pm]
我该如何解决这个问题?
答案 0 :(得分:1)
r = /
(?<= # begin a positive lookbehind
\d # match a digit
[ap] # match 'a' or 'p'
m # match 'm'
) # end positive lookbehind
(?= # begin a positive lookahead
\d # match a digit
) # end positive lookahead
/x # free-spacing regex definition mode
"8pm9pm8pm7pm-10pm".split r
#=> ["8pm", "9pm", "8pm", "7pm-10pm"]
以常规(非自由间隔模式)方式表示,正则表达式如下。
r = /(?<=\d[ap]m)(?=\d)/
请注意,正向后观跟随正向前瞻有效地将字符串分割为字符。
答案 1 :(得分:0)
这个正则表达式Kayla怎么样? /((?:\+|-)?\d*(?:am|pm))/i
"8pm9pm8pm7pm-10pm8AM".split(/((?:\+|-)?\d*(?:am|pm))/i).reject(&:empty?)
[
[0] "8pm",
[1] "9pm",
[2] "8pm",
[3] "7pm",
[4] "-10pm",
[5] "8AM"
]
我们注意:
?:
的分组匹配)?:
i
选项答案 2 :(得分:0)
你真的需要正则表达式吗?如果不是,字符串方法是另一种选择:
"8pm9pm8pm7pm-10pm8AM".gsub("pm", "pm ").gsub(" -", "-") #=> "8pm 9pm 8pm 7pm-10pm 8AM"
为您提供所需的字符串,或
"8pm9pm8pm7pm-10pm8AM".gsub("pm", "pm ").gsub(" -", "-").split(" ") #=> ["8pm", "9pm", "8pm", "7pm-10pm", "8AM"]
如果你真的想要它作为一个字符串数组。