如何使用正则表达式打印重复的输出,它只打印第一个匹配项。

huangapple go评论67阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月21日 02:00:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定