-1

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

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
4

3 回答 3

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"]
于 2013-07-11T19:56:41.993 回答
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}) 后跟aOR p+m然后是另一个所有内容,直到...

for很简单。

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

/gm告诉正则表达式是 Global 和 Multi-line

于 2013-07-11T19:55:43.007 回答
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"
于 2013-07-11T19:54:17.840 回答