我正在创建一个事件,我希望能够解析单个字符串并填充模型的属性。例如,我想做以下操作:
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 = $1nndate_time = $2nnduration = $3
工作示例:http://regexr.com?35i10
解释:
^
表示我们希望从行的开头开始
CCD_ 2意味着在第一个变量中存储直到CCD_。
(d{1,2}[a|p]m.*)
表示一个1或2位数字(d{1,2}
),后跟a
或p
+m
,然后是另一个所有数字,直到。。。
CCD_ 9足够简单。
(.*)$
意味着存储所有内容直到行结束。
/gm
告诉正则表达式为全局和多行
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"