Looping through python regex matches

China☆狼群 提交于 2019-12-03 01:18:06

问题


This has to be easier than what I am running into. My problem is turning a string that looks like this:

ABC12DEF3G56HIJ7

into

12 * ABC
3  * DEF
56 * G
7  * HIJ

And I can't, for the life of me, design a correct set of loops using REGEX matching. The crux of the issue is that the code has to be completely general because I cannot assume how long the [A-Z] fragments will be, nor how long the [0-9] fragments will be.

Thank you for any assistance!


回答1:


Python's re.findall should work for you.

Live demo

import re

s = "ABC12DEF3G56HIJ7"
pattern = re.compile(r'([A-Z]+)([0-9]+)')

for (letters, numbers) in re.findall(pattern, s):
    print(numbers, '*', letters)



回答2:


It is better to use re.finditer if you dataset is large:

import re

s = "ABC12DEF3G56HIJ7"
pattern = re.compile(r'([A-Z]+)([0-9]+)')

for m in re.finditer(pattern, s):
    print m.group(2), '*', m.group(1)


来源:https://stackoverflow.com/questions/12870178/looping-through-python-regex-matches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!