正则表达式将数字与Alpha分开

时间:2010-01-29 11:21:52

标签: python regex

我有一堆字符串:

"10people"
"5cars"
..

我如何将其拆分为?

['10','people']
['5','cars']

它可以是任意数量的数字和文字。

我正在考虑编写某种正则表达式 - 但我确信在Python中有一种简单的方法。

7 个答案:

答案 0 :(得分:8)

使用正则表达式(\d+)([a-zA-Z]+)

import re
a = ["10people", "5cars"]
[re.match('^(\\d+)([a-zA-Z]+)$', x).groups() for x in a]

结果:

[('10', 'people'), ('5', 'cars')]

答案 1 :(得分:8)

>>> re.findall('(\d+|[a-zA-Z]+)', '12fgsdfg234jhfq35rjg')
['12', 'fgsdfg', '234', 'jhfq', '35', 'rjg']

答案 2 :(得分:3)

>>> re.findall("\d+|[a-zA-Z]+","10people")
['10', 'people']

>>> re.findall("\d+|[a-zA-Z]+","10people5cars")
['10', 'people', '5', 'cars']

答案 3 :(得分:2)

通常,/(?<=[0-9])(?=[a-z])|(?<=[a-z])(?=[0-9])/i上的拆分会将字符串分开。

答案 4 :(得分:0)

>>> import re
>>> s = '10cars'
>>> m = re.match(r'(\d+)([a-z]+)', s)
>>> print m.group(1)
10
>>> print m.group(2)
cars

答案 5 :(得分:0)

如果你像我一样长时间徘徊以避免正则表达,因为它们很难看,这是一种非正则表达方式:

data = "5people10cars"

numbers = "".join(ch if ch.isdigit() else "\n" for ch in data).split()
names = "".join(ch if not ch.isdigit() else "\n" for ch in data).split()

final = zip (numbers, names)

答案 6 :(得分:0)

使用str.translate抄袭jsbueno的想法,然后拆分:

import string

allchars = ''.join(chr(i) for i in range(32,256))
digExtractTrans = string.maketrans(allchars, ''.join(ch if ch.isdigit() else ' ' for ch in allchars))
alpExtractTrans = string.maketrans(allchars, ''.join(ch if ch.isalpha() else ' ' for ch in allchars))

data = "5people10cars"
numbers = data.translate(digExtractTrans).split()
names = data.translate(alpExtractTrans).split()

您只需创建一次翻译表,然后根据需要随时调用翻译和拆分。

相关问题