[Tutor] Regular expression questions

Bernard Lebel 3dbernard at gmail.com
Thu May 3 18:04:41 CEST 2007


Once again struggling with regular expressions.

I have a string that look like "something_shp1".
I want to replace "_shp1" by "_shp". I'm never sure if it's going to
be 1, if there's going to be a number after "_shp".

So I'm trying to use regular expression to perform this replacement.
But I just can't seem to get a match! I always get a None match.

I would think that this would have done the job:

r = re.compile( r"(_shp\d)$" )

The only way I have found to get a match, is using

r = re.compile( r"(\S+_shp\d)$" )

My second question is related more to the actual string replacement.
Using regular expressions, what would be the way to go? I have tried
the following:

newstring = r.sub( '_shp', oldstring )

But the new string is always "_shp" instead of "something_shp".


More information about the Tutor mailing list