[Tutor] Regular expression questions
kent37 at tds.net
Thu May 3 21:43:45 CEST 2007
Bernard Lebel wrote:
> 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 guess is you are calling r.match() rather than r.search(). r.match()
only looks for matches at the start of the string; r.search() will find
a match anywhere.
> 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".
Because your re matches something_shp.
newstring = re.sub('_shp\d' '_shp', oldstring )
will do what you want.
More information about the Tutor