I'm trying to do a simple regex split in Python. The string is in the form of FooX where Foo is some string and X is an arbitrary integer. I have a feeling this should be really simple, but I can't quite get it to work.
On that note, can anyone recommend some good Regex reading materials?
You can't use split()
since that has to consume some characters, but you can use normal matching to do it.
>>> import re
>>> r = re.compile(r'(\D+)(\d+)')
>>> r.match('abc444').groups()
('abc', '444')
Using groups:
import re
m=re.match('^(?P<first>[A-Za-z]+)(?P<second>[0-9]+)$',"Foo9")
print m.group('first')
print m.group('second')
Using search:
import re
s='Foo9'
m=re.search('(?<=\D)(?=\d)',s)
first=s[:m.start()]
second=s[m.end():]
print first, second
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With