Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex split, integer of arbitrary length

Tags:

python

regex

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?

like image 618
user131091 Avatar asked Feb 27 '23 16:02

user131091


2 Answers

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')
like image 83
Max Shawabkeh Avatar answered Mar 07 '23 15:03

Max Shawabkeh


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
like image 24
AJ. Avatar answered Mar 07 '23 14:03

AJ.