Python:根据字母提取数字

时间:2018-12-11 18:50:14

标签: python regex numbers extract

我有一个字符串(“ 1x5y”),我想从中提取数字,但是我想根据字母来提取这些数字。在我的字符串中,我想以x = 1和y = 5结尾。
另外,字符串中可能存在x或y,也可能不存在,但始终会存在至少一个(并且仅存在一次,且不超过一次)。
我设法使用正则表达式和一些“ if”来做到这一点,但我想知道是否有更优雅的解决方案。

谢谢

编辑:这是我所拥有的

delta = "2y"
if ("x" in delta) and ("y" in delta):
    x = re.findall('\d+',str(re.findall('\d+x',delta)))
    y = re.findall('\d+',str(re.findall('\d+y',delta)))
elif ("x" in delta) and ("y" not in delta):
    x = re.findall('\d+',str(re.findall('\d+x',delta)))
elif ("x" not in delta) and ("y" in delta):
    y = re.findall('\d+',str(re.findall('\d+y',delta)))
else:
    x = y = 0

2 个答案:

答案 0 :(得分:1)

解决此问题的最基本,最幼稚的正则表达式是(\d+)([a-zA-Z]),并且不需要任何if。捕获组将注意将每个数字“关联”到其右侧的字母上。

import re

regex = re.compile(r'(\d+)([a-zA-Z])')
for string in ['1x5y', '1x', '5y', '111x2y333z']:
    print(string)
    for number, letter in regex.findall(string):
        print(number, letter)
    print()

输出

1x5y
1 x
5 y

1x
1 x

5y
5 y

111x2y333z
111 x
2 y
333 z

答案 1 :(得分:0)

您可以预编译正则表达式并用findall()分配

import re

s = "1x5y"
p = re.compile(r'(\d+)x(\d+)y')
(x, y) = re.findall(p, s)[0]
相关问题