sixD
sixD

Reputation: 227

Python 3 find a string between two points

I've had this working fine in py2.7, but am having trouble getting it to now work in in py3 with the changes to regex

i just want the string "voltaire" returned from a file name

gpxFileName = '235235voltaire.gpx'
m=re.search('(?<=[0-9]).*?(?=.gpx)',gpxFileName)
print (m.group(1))

the above code successfully prunes off the .gpx fine, but the numbers stay in :(

i've been stuck on this for waaaaay too long, and its KILLING me. wot am i missing??

btw, i have also tried

m=re.search('(?<=[0-9])\w+',gpxFileName)

and

m=re.search('(?<=\d).*(?=.gpx)',gpxFileName)

Upvotes: 2

Views: 446

Answers (1)

alecxe
alecxe

Reputation: 474003

You need to use capturing groups:

>>> import re
>>> s = '235235voltaire.gpx'
>>> re.search(r'\d+(\w+)\.gpx', s).group(1)
'voltaire'

Here we are extracting one or more alphanumeric characters right after one or more digits and right before the .gpx (dot has to be escaped since it has a special meaning).

Upvotes: 4

Related Questions