python - 仅在第一次使用正则表达式时使用多个分隔符分隔
问题描述
我有一些格式为的字符串
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 个匹配,但已经匹配的选项除外。
^(.*?)(, | - |: )(.*?)(?!\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
推荐阅读
- list - PowerQuery:如何用多列的每列名称替换文本
- bash - 使用 bash 获取活动的 kerberos 主体
- javascript - Javascript在恢复功能之前等待按钮按下
- angular - 垫子图标不显示
- javascript - 如何使用 .env 文件制作登录屏幕?
- swift - RxSwift 和 AVKit 的问题
- python-3.x - 如何在 PyQt5 的列表小部件中添加图像?
- javascript - 带有 useEffect 和 React Native 的 socket.IO 不会多次更新 Redux 状态
- excel - 有没有办法在 32 位 Excel 的 VBA 中存储 64、128 或 256 字节值?
- html - 超过页面末尾的下拉菜单