简体   繁体   English

循环遍历python正则表达式匹配

[英]Looping through python regex matches

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.而且我一生都无法使用 REGEX 匹配设计一组正确的循环。 The crux of the issue is that the code has to be completely general because I cannot assume how long the [AZ] fragments will be, nor how long the [0-9] fragments will be.问题的关键是代码必须是完全通用的,因为我无法假设[AZ]片段的长度,也无法假设[0-9]片段的长度。

Thank you for any assistance!感谢您的任何帮助!

Python's re.findall should work for you. Python 的re.findall应该适合你。

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)

It is better to use re.finditer if your dataset is large because that reduces memory consumption ( findall() return a list of all results, finditer() finds them one by one).如果您的数据集很大,最好使用re.finditer ,因为这样可以减少内存消耗( findall()返回所有结果的列表, finditer()一个一个地找到它们)。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM