我有一个带有可选子字符串的字符串,我正在寻找/正在寻找/研究带有名称捕获的正则表达式,如果可能的话,所有的正则表达式。
在 ruby 中
请帮忙,
示例字符串:
string1 = bike wash #a simple task
string2 = bike wash @ bike point # a simple task with location
string3 = bike wash @ bike point on 13 may 11 # task with location and date
string4 = bike wash @ bike point on 13 may 11 @ 10 AM # task with location, date and time
string5 = bike wash on 13 may 11 @ 10 AM # task with date and time without location
string6 = bike wash on 13 may 11 # task and date
我在 google 和 stackoverflow 上花了将近一天的时间来为上述所有字符串模式获取一个正则表达式。
最佳答案
假设:
- 地点和时间以
@
开头,@
无处出现。 - 日期以
on
开头,周围是强制性的空格,并且on
没有出现在其他地方。 - 任务是强制性的。
- 地点和日期是可选的,并且彼此独立。
- 只有在有日期时才会出现时间。
- 任务、地点、日期、时间只按这个顺序出现。
此外,既然提到了命名捕获,那么理所当然地认为正则表达式引擎是oniguruma。
regex = /
(?<task>.*?)
(?:\s*@\s*(?<location>.*?))?
(?:\s+on\s+(?<date>.*?)
(?:\s*@\s*(?<time>.*))?
)?
\z/x
string4.match(regex)
# => #<MatchData
"bike wash @ bike point on 13 may 11 @ 10 AM"
task: "bike wash"
location: "bike point"
date: "13 may 11"
time: "10 AM"
>
关于ruby - ruby 中用于具有多种模式的字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5933498/