Regex for splitting a number from Alpha

I have a string chain:

"10people" "5cars" .. 

How would I divide this into?

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

It can be any number of numbers and text.

I'm thinking of writing some kind of regex, however I'm sure there is an easy way in Python to do this.

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

Use the regular expression (\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')] 
+8
source
 >>> re.findall("\d+|[a-zA-Z]+","10people") ['10', 'people'] >>> re.findall("\d+|[a-zA-Z]+","10people5cars") ['10', 'people', '5', 'cars'] 
+3
source

In general, dividing by /(?<=[0-9])(?=[az])|(?<=[az])(?=[0-9])/i thus splits the string.

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

If you are like me and go around long loops to avoid regular expressions because they are ugly, here is a non-regular expression approach:

 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) 
0
source

Piggybacking on the idea of ​​jsbueno using str.translate and then split:

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

You only need to create the translation tables once, and then translate and split as often as you want.

0
source

Source: https://habr.com/ru/post/1299731/


All Articles