regex 关键字后的分组字符串(at,after,until)忽略顺序

bvn4nwqk  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(148)

我想分组任何文本后,这些关键字之一
输入:/send 1 at 11:00pm for 3min
预期结果:postNumber = 1, sendAt = 11:00pm, duration = 3min
输入:/send 1 for 3min
预期结果:postNumber = 1, duration = 3min
输入:/send 1 at 11:00pm
预期结果:postNumber = 1, sendAt = 11:00pm
输入:/send 1 until 11:00pm
预期结果:postNumber = 1, until = 11:00pm
输入:/send 1 for 3min at 11:00 pm
预期结果:postNumber = 1, sendAt = 11:00 pm, duration = 3min
输入:/send 1 at 11am for 1 h
预期结果:postNumber = 1, sendAt = 11am, duration = 1 h
我已经做了下面的正则表达式,但不知道如何使它不可知的关键字输入顺序
(?<postNumber>\d+)(?: at (?<sendAt>.*))?(?: for (?<duration>.*))?(?: until (?<until>.*))?
我尝试添加正提前锁定,但它匹配第一组(?<postNumber>\d+)(?=(?: at (?<timeToSend>.*)))?(?=(?: for (?<duration>.*)))?(?=(?: until (?<until>.*)))?中的所有数字

xe55xuns

xe55xuns1#

您可以将每个捕获组包含在一个正向前模式中,以便可以按任何顺序匹配它们:

\/send\s+(?<postNumber>\d+)(?=(?:.*\bat\s+(?<sendAt>\d+(?::\d+)?\s*\S+))?)(?=(?:.*\bfor\s+(?<duration>\d+\s*\S+))?)(?=(?:.*\buntil\s+(?<until>\d+(?::\d+)?\s*\S+))?)

演示:https://regex101.com/r/Ks5YHN/2

相关问题