![](/img/trans.png)
[英]Regex to get all occurrences of a pattern followed by a value in a comma separate string
[英]get all occurrences from a matched pattern and split
我正在使用以下代码查找从索引 0 到 ~ 的所有索引,因此我可以从每个匹配项中创建一行
import re
s = 'product 1 & product 2|category 1|8~product 4|category 3 |10~product 1 & product 19|category 8|6~product 50|category 4|6'
substring = "~"
matches = re.finditer(substring, s)
matches_positions = [match.start() for match in matches]
print(matches_positions)
output
[34, 59, 95]
我手动使用每个索引以显示以下 output,我想创建一个 function 可以拆分并返回每个事件
print(s[0:34])
print(s[34 + 1: 59])
print(s[59 +1 : 95])
print(s[95 +1 : len(s)])
output
product 1 & product 2|category 1|8
product 4|category 3 |10
product 1 & product 19|category 8|6
product 50|category 4|6
事先谢谢你
您只需要使用内置的str.split
function:
outputs = s.split('~')
这是outputs
值:
['product 1 & product 2|category 1|8',
'product 4|category 3 |10',
'product 1 & product 19|category 8|6',
'product 50|category 4|6']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.