英文:
How do i print the repetition output using regex it prints only first match
问题
我需要打印出现次数和计数以及未出现次数和计数。
import re
sequence = '1222311'
m = re.search(r'(\d)+', sequence)
print(m)
期望输出:
(1, 1) (3, 2) (1, 3) (2, 1)
在序列中需要检查并打印
(cnt , val) -> 1222311 -> 1仅出现一次 -> (1, 1) (cnt, number)
英文:
I have task where I need to print the occurrence and count and non-occurrence and count
import re
sequence = '1222311'
m = re.search(r'(\d)+',sequence)
print(m)
Exptected output :
(1, 1) (3, 2) (1, 3) (2, 1)
In sequence need to check and print
(cnt , val) -> 1222311 -> 1 as come only once -> (1,1) (cnt,number)
答案1
得分: 2
你可以使用 re.finditer
来获取匹配的起始和结束索引,然后构建你的输出(regex101):
import re
sequence = '1222311'
out = [(m.end() - m.start(), int(m.group(1))) for m in re.finditer(r'(\d)*', sequence)]
print(out)
输出:
[(1, 1), (3, 2), (1, 3), (2, 1)]
英文:
You can use re.finditer
to get start/end index of match and then construct your output (regex101):
import re
sequence = '1222311'
out = [(m.end() - m.start(), int(m.group(1))) for m in re.finditer(r'(\d)*', sequence)]
print(out)
Prints:
[(1, 1), (3, 2), (1, 3), (2, 1)]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论