gpt4 book ai didi

python - 仅在第一个实例中使用正则表达式使用多个分隔符分隔

转载 作者:行者123 更新时间:2023-12-02 02:40:08 25 4
gpt4 key购买 nike

我有一些格式为的字符串

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"]

最佳答案

如果所有分隔符必须至少出现一次,您可以使用 4 个捕获组,并使用反向引用匹配 3 个选项中的 1 个(已匹配的选项除外),而不是使用 split。

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

模式将匹配

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

Regex demo

例如

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 demo1demo2

关于python - 仅在第一个实例中使用正则表达式使用多个分隔符分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63765561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com