![](/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.