user2862886
user2862886

Reputation: 51

\0 doesn't work in re.sub(). way around?

In Python,

re.sub('(ab)c', r'\1d', 'xxxabcxxx') 

gives me back 'xxxabdxxx'.

You would expect re.sub('(ab)c', r'\0d', 'xxxabcxxx') to return 'xxxabcdxxx'. That is, you'd expect it to work in a similar way to m.group(0).

However, this isn't supported. http://bugs.python.org/issue17426#msg184210

What is a simple way to achieve what re.sub('(ab)c', r'\0d', 'xxxabcxxx') should achieve, without the use of re.sub()?

Upvotes: 5

Views: 514

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191789

Use \g<0>. You can also use \g<1>, etc. for other groups, but 0 is the entire match.

This is explained in the documentation: http://docs.python.org/2/library/re.html#re.sub

Upvotes: 11

Related Questions