首页 > 解决方案 > 仅在第一次使用正则表达式时使用多个分隔符分隔

问题描述

我有一些格式为的字符串

lorem ipsum, dolor sit - amet, consectetur : adipiscing elit. Praesent vitae orc

我希望它在每个分隔符的第一个实例处拆分,返回

['lorem ipsum',
'dolor sit', 
'amet, consectetur', 
'adipiscing elit. Praesent vitae orc']

现在我的输出是

['lorem ipsum',
'dolor sit',
'amet',
'consectetur ',
'adipiscing elit. Praesent vitae orc']

现在我正在使用re.split(', | - |: ', txt),但它在字符串中的所有实例处分开。关于如何实现所需输出的任何建议?

编辑:

我意识到我的问题并不清楚,例如,如果字符串是

"abc: def: ijk, lmno: pqr - stu, wx"

输出应该是

["abc",
"def: ijk",
"lmno: pqr",
"stu, wxy"]

并不是

["abc",
"def",
"ijk",
"lmno",
"pqr",
"stu",
"wxy"]

标签: pythonregex

解决方案


如果所有分隔符必须至少出现一次,则可以使用 4 个捕获组,其反向引用与 3 个选项中的 1 个匹配,但已经匹配的选项除外。

^(.*?)(, | - |: )(.*?)(?!\2)(, | - |: )(.*?)(?!\2|\4)(, | - |: )(.*)

模式将匹配

  • ^字符串的开始
  • (.*?)1组,尽可能少匹配
  • (, | - |: )2组,匹配任何列出的
  • (.*?)3组,尽可能少匹配
  • (?!\2)负前瞻,断言右侧的内容不是第 2 组中匹配的内容(选择 2 个有效选项之一)
  • (, | - |: )4组,匹配任何列出的
  • (.*?)5组,尽可能少匹配
  • (?!\2|\4)负前瞻,断言右边的不是第 2 组或第 4 组中匹配的(选择左边唯一有效的选项)
  • (, | - |: )6组,匹配任何列出的
  • (.*)7组,尽可能匹配任何字符

正则表达式演示

例如

import re

regex = r"^(.*?)(, | - |: )(.*?)(?!\2)(, | - |: )(.*?)(?!\2|\4)(, | - |: )(.*)"

test_str = ("lorem ipsum, dolor sit - amet , consectetur : adipiscing elit. Praesent vitae orc\n\n"
    "abc: def: ijk, lmno: pqr - stu, wx\n\n")

matches = re.search(regex, test_str, re.MULTILINE)

if matches:
    print(matches.group(1))
    print(matches.group(3))
    print(matches.group(5))
    print(matches.group(7))

输出

lorem ipsum
dolor sit
amet , consectetur 
adipiscing elit. Praesent vitae orc

请参阅 Python演示 1演示2


推荐阅读