匹配书面列表的正则表达式,例如 "New York, Texas, and Florida"

Regex matching a written list such as "New York, Texas, and Florida"

我需要一个正则表达式来匹配任意长列表的以下条件,其中每个捕获可以是 多个单词。如果有帮助,它将始终带有牛津逗号。

  1. 'New York' #=> ['New York']

  2. 'New York and Texas' #=> ['New York', 'Texas']

  3. 'New York, Texas, and Florida' #=> ['New York', 'Texas', 'Florida']

我发现 (.+?)(?:,|$)(?:\sand\s|$)? 会匹配 1 和 3 但不会匹配 2。

并且 (.+?)(?:\sand\s|$) 将匹配 1 和 2 但不匹配 3。

如何匹配所有 3 个?

您可以使用以下模式拆分文本:

(?:\s*(?:\band\b|,))+\s*

详情

  • (?:\s*(?:\band\b|,))+ - 出现 1 次或多次:
    • \s* - 0+ 个空格
    • (?:\band\b|,) - and 作为一个完整的词或一个逗号
  • \s* - 0 个或多个空白字符。

参见regex demo

请注意,如果您的正则表达式引擎支持所有格量​​词,您可能会提高效率:

(?:\s*+(?:\band\b|,))+\s*
      ^

或原子团:

(?>\s*+(?:\band\b|,))+\s*
 ^^