Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to separate Numeric from Alpha

Tags:

python

regex

I have a bunch of strings:

"10people"
"5cars"
..

How would I split this to?

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

It can be any amount of numbers and text.

I'm thinking about writing some sort of regex - however I'm sure there's an easy way to do it in Python.

like image 488
Federer Avatar asked Nov 29 '22 19:11

Federer


2 Answers

>>> re.findall('(\d+|[a-zA-Z]+)', '12fgsdfg234jhfq35rjg')
['12', 'fgsdfg', '234', 'jhfq', '35', 'rjg']
like image 58
Ignacio Vazquez-Abrams Avatar answered Dec 06 '22 08:12

Ignacio Vazquez-Abrams


Use the regex (\d+)([a-zA-Z]+).

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

Result:

[('10', 'people'), ('5', 'cars')]
like image 23
kennytm Avatar answered Dec 06 '22 09:12

kennytm