How to use a regular expression to separate numbers and characters in strings like "30M1000N20M"

I am trying to highlight [0-9]and [A-Z]in such lines:

100M
20M1D80M
20M1I79M
20M10000N80M

I tried using the Python module re, and the following code I used:

>>>import re
>>>num_alpha = re.compile('(([0-9]+)([A-Z]))+')
>>>str1="100M"
>>>n_a_match = num_alpha.match(str1)
>>>n_a_match.group(2), n_a_match.group(3)

100,M   #just what I want

>>>str1="20M10000N80M"
>>>n_a_match = num_alpha.match(str1)
>>>n_a_match.groups()

('80M', '80', 'M')  #only the last one, how can I get the first two?
#expected result ('20M','20','M','10000N','10000','N','80M','80','M')

This regex works well for strings that contain only one match, but not multiple match groups. How can I handle this with regular expressions?

+5
source share
3 answers

I suggest using re.findall. If you intend to iterate over the results rather than creating a list, you can use instead re.finditer. Here is an example of how this will work:

>>> re.findall("(([0-9]+)([A-Z]))", "20M10000N80M")
[('20M', '20', 'M'), ('10000N', '10000', 'N'), ('80M', '80', 'M')]

+ , :

>>> re.findall("([0-9]+)([A-Z])", "20M10000N80M")
[('20', 'M'), ('10000', 'N'), ('80', 'M')]

, ( , , ), :

>>> re.findall("([0-9]+|[A-Z])", "20M10000N80M")
['20', 'M', '10000', 'N', '80', 'M']
+3

split:

>>> str1="20M10000N80M"
>>> num_alpha = re.compile('(([0-9]+)([A-Z]))')
>>> l = num_alpha.split(str1)
>>> l
['', '20M', '20', 'M', '', '10000N', '10000', 'N', '', '80M', '80', 'M', '']

, + .

, :

>>> l_without_empty = [x for x in l if x != '']
['20M', '20', 'M', '10000N', '10000', 'N', '80M', '80', 'M']

Edit:

, :

>>> l_without_empty = [x for x in l if x]
['20M', '20', 'M', '10000N', '10000', 'N', '80M', '80', 'M']
+3

re.findall:

>>> string = "20M10000N80M"
>>> groups = re.findall(r'((\d+)(\D+))', string)
[('20M', '20', 'M'), ('10000N', '10000', 'N'), ('80M', '80', 'M')]

, , , , , , , :

>>> from itertools import chain
>>> tuple(chain.from_iterable(groups))
('20M', '20', 'M', '10000N', '10000', 'N', '80M', '80', 'M')
+2

All Articles