我正在创建一个事件,我希望能够解析单个字符串并填充模型的属性。例如,我想做以下事情:
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
如果您总是要使用该格式,您可以执行以下操作:
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"]
以下内容应该适合您:
/^(.*) at (\d{1,2}[a|p]m.*) for (.*)$/gm
在替换中,您将使用:
title = $1\n\ndate_time = $2\n\nduration = $3
说明:
^
表示我们要从行首开始
(.*) at
表示将所有内容存储到at
第一个变量中。
(\d{1,2}[a|p]m.*)
表示 1 或 2 位数字 ( \d{1,2}
) 后跟a
OR p
+m
然后是另一个所有内容,直到...
for
很简单。
(.*)$
表示将所有内容存储到行尾。
/gm
告诉正则表达式是 Global 和 Multi-line
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"