在ruby中,如何仅使用最后一个单词将字符串拆分为数组

时间:2013-07-11 19:48:22

标签: ruby regex arrays parsing split

我正在创建一个事件,我希望能够解析单个字符串并填充模型的属性。举个例子,我想做以下几点:

string = "Workout at the gym at 7pm on July 4th for 1 hour"

从这个字符串中,我想设置以下变量:

title = Workout at the gym

date_time = 7pm on July 4th

duration = 1 hour

3 个答案:

答案 0 :(得分:1)

如果你总是打算使用这种格式,你可以这样做:

re = string.match(/(?<title>.*) at (?<date_time>.*) for (?<duration>.*)/)
title, date_time, duration = re[:title], re[:date_time], re[:duration]
# ["Workout at the gym", "7pm on July 4th", "1 hour"]

答案 1 :(得分:0)

str = "Workout at the gym at 7pm on July 4th for 1 hour"
a = str.split(/at|for/).map(&:strip)
# => ["Workout", "the gym", "7pm on July 4th", "1 hour"]
duration,date_time,title = a.pop,a.pop,a.join(" ")
duration # => "1 hour"
date_time # => "7pm on July 4th"
title # => "Workout the gym"

答案 2 :(得分:0)

以下内容对您有用:

/^(.*) at (\d{1,2}[a|p]m.*) for (.*)$/gm

在替换中,您将使用:

title = $1\n\ndate_time = $2\n\nduration = $3

工作示例:http://regexr.com?35i10

<强>解释

^表示我们想要从行的开头

开始

(.*) at表示将第一个变量中的所有内容存储到at

(\d{1,2}[a|p]m.*)表示1位或2位数字(\d{1,2}),后跟ap + m,然后是其他所有内容,直到...

for很简单。

(.*)$表示将所有内容存储到行尾。

/gm告诉正则表达式为全局和多行