Sto cercando di separare il [0-9]
e [A-Z]
nelle stringhe come questi:Come usare espressioni regolari per separare numeri e caratteri in stringhe come "30M1000N20M"
100M
20M1D80M
20M1I79M
20M10000N80M
Ho provato ad utilizzare il modulo Python re
, e quello che segue è il codice che ho usato:
>>>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')
Questa espressione regolare funziona bene per le stringhe che contengono solo una partita, ma non diversi gruppi di partite. Come posso gestirlo usando le espressioni regolari?
Grande. Non ho ricordato la funzione 'findall()'. Apprezza l'ultima espressione regolare. – ct586
Tutte le risposte sono fantastiche. Se permesso, sceglierei tutti e tre. Ho scelto questo per la seconda espressione regolare dà esattamente quello che voglio. Ancora una volta, grazie a tutti. – ct586