循环通过 python regex 匹配

这肯定比我碰到的要容易。我的问题是转动这样的字符串:

ABC12DEF3G56HIJ7

进入

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

我无论如何也不能使用 REGEX 匹配设计一组正确的循环。问题的关键在于代码必须是完全通用的,因为我不能假设 [A-Z]片段会有多长,也不能假设 [0-9]片段会有多长。

谢谢你的帮助!

114429 次浏览

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)

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

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)