用于匹配由“,”或“和”

时间:2017-03-30 10:24:12

标签: regex pcre

我希望与此匹配:first, second, third and fourth section并获取不同的部分:

匹配1:first

匹配2:second

匹配3:third

匹配4:fourth

字符串部分也必须以单词section结尾。如果没有,则应删除所有匹配。

如何使用正则表达式实现这一目标?到目前为止我试过这个: https://regex101.com/r/Qwnh6m/3

(?P<section>(first|second|third|fourth)(?=(\ssection|\sog\s(first|second|third|fourth)\ssection|,\s(first|second|third|fourth))))

注意:正则表达式适用于这样的字符串非常重要。

something else lalala and then first, second, third and fourth section something more.

1 个答案:

答案 0 :(得分:1)

你可以使用lookaheads来使用这个正则表达式:

\b(first|second|third|fourth)(?=,|\h+(?:and|section)\b)(?=.*\hsection\b)

RegEx Demo

RegEx分手:

  • \b(first|second|third|fourth) - 匹配组中的1个或多个给定字词
  • (?= - 开始前瞻
    • , - 包含逗号
    • | - 或
    • \h+ - 1个或更多水平空格
    • (?: - 启动非捕获组
      • and - 包含“”字样
      • | - 或
      • section$ - 字“部分
    • ) - 结束非捕获组
    • \b - 字边界
  • ) - 结束前瞻
  • (?= - 开始第二次前瞻
    • .*section\b - 包含“部分”字样
  • ) - 结束第二次前瞻

编辑:这是进一步修复后的最终正则表达式: \b(first|second|third|fourth)(?=(?:\s*(?:,|and)\s*(?:first|second|third|fourth))*\s+section\b)

https://regex101.com/r/NXVwZl/21