用于匹配由“,”或"and"分隔的项目列表的正则表达式

Regext for matching a listing of items separated by "," or "and"

我想匹配这个: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.

您可以通过先行使用此正则表达式:

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

RegEx Demo

正则表达式分解:

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

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

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