Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

regex

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()?

like image 882
user2862886 Avatar asked Dec 26 '22 19:12

user2862886


1 Answers

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

like image 131
Explosion Pills Avatar answered Dec 28 '22 10:12

Explosion Pills