ruby中的正则表达式,用于具有多个模式的字符串

我有一个带有可选子串的字符串,我正在寻找/正常表达式上使用名称捕获,如果可能的话,为所有人提供单个正则表达式。

在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其他任何地方都没有出现。
  • 任务是强制性的。
  • 位置和日期是可选的,彼此独立。
  • 时间仅在有日期时出现。
  • 任务,位置,日期,时间仅按此顺序显示。

此外,应该理所当然地认为正则表达式引擎是oniguruma,因为提到了命名捕获。

 regex = / (?.*?) (?:\s*@\s*(?.*?))? (?:\s+on\s+(?.*?) (?:\s*@\s*(? 

对于正则表达式来完成这项工作,需要做一些假设。 任务不应包括“@”或“on”,例如,但可能还有更多。

要匹配任何字符,但第一个空格为“@”或“on”,我会使用(?! @ | on ). 所以你可以使用(((?! @ | on ).)+)找到任务。 接下来是一个可选的位置,前缀为“@”: (?: @ ((?:(?! on ).)+))? 。 请注意,此处的位置不应包含“on”。

接下来,有一个可选日期和可选时间(?: on ((?:(?! @ ).)+)(?: @ (.+))?)? 。 全部一起:

 ((?:(?! @ | on ).)+)(?: @ ((?:(?! on ).)+))?(?: on ((?:(?! @ ).)+)(?: @ (.+))?)? 

这将在前四个捕获组中具有任务,位置,日期和时间。 见这里: http : //regexr.com?2tnb3