首页 > 解决方案 > Python: how to split string by groups Alpha-numeric vs numeric

问题描述

Lets say I have Strings like: "H39_M1", "H3_M15", "H3M19", "H3M11", "D363_H3", "D_128_H17_M50"

How can I split them every single one into a list of substrings? like this:

["H39", "M1"], "[H3, "Min15"], ["H3","M19"], ["H3","M11"], ["D363","H3"], ["D128","H17","M50"]

and afterwards: switch places of alphanumeric-group and numeric group, like this: ["39H", "1M"], "[3H, "15Min"], ["3H","19M"], ["3H","11M"], ["363D","3H"],["128D","17H","50M"]

length of numbers-group and of alphanumeric group varys as you can see. also "_" underscores can divide them.

标签: pythonstringsubstringnumericalphanumeric

解决方案


我可能会建议re.findall在这里使用re.sub

inp = "H3M19"
inp = re.sub(r'([A-Z]+)([0-9]+)', r'\2\1', inp)
parts = re.findall(r'[0-9]+[A-Z]+', inp)
print(parts)

这打印:

['3H', '19M']

第一步re.sub转换H3M193H19M, 通过捕获字母和数字对然后交换它们。然后,我们使用re.findall在交换的输入中查找所有数字/字母对。


推荐阅读