This article uses Python 2.7 for verification.
When you want to do a group substitution of a regular expression using re.sub ()
, you usually write it like this.
(* Be careful to write '\'
twice before group number 1)
python
re.sub(r'(hoge)', '\\1bar', 'hogefoo')
#result:
# 'hogebarfoo'
However, with this writing method, if you want to put a number after the ** group number, you will get the following error. ** **
python
# 'Third'To'number 3'Want to
re.sub(r'(No.)three', '\\13', 'No.three')
#result:
# ...
# raise error, "invalid group reference"
# sre_constants.error: invalid group reference
This is because the group number is recognized as 13 (in the above example) instead of 1.
In such a case, you can solve it by writing as follows.
python
re.sub(r'(No.)three', '\g<1>3', 'No.three')
#result:
#number 3
Recommended Posts