Groupings and backreferences | Python regex replace group
ThischapterwillshowhowtoreuseportionmatchedbycapturegroupsviabackreferenceswithinREdefinitionandreplacementsection.Youllalsolearnsomeofthespecialgroupingsyntaxforcaseswhereplaincapturegroupsisntenough.Backreferencesarelikevariablesinaprogramminglanguage.Youhavealreadyseenhowtousere.Matchobjecttorefertothetextcapturedbygroups.Backreferencesprovidethesamefunctionality,withtheadvantagethatthesecanbedirectlyusedinREdefinitionaswellasreplacementsectionwithouthavingtoinvokere.Matchobjects.Anothera...
This chapter will show how to reuse portion matched by capture groups via backreferences within RE definition and replacement section. Youll also learn some of the special grouping syntax for cases where plain capture groups isnt enough.
Backreferences are like variables in a programming language. You have already seen how to use re.Match object to refer to the text captured by groups. Backreferences provide the same functionality, with the advantage that these can be directly used in RE definition as well as replacement section without having to invoke re.Match objects. Another advantage is that you can apply quantifiers to backreferences.
The syntax is N or g<N> where N is the capture group you want. The below syntax variations is applicable for replacement section, assuming they are used within raw strings.
1, 2 up to 99 to refer to the corresponding capture group provided there are no digit characters after and NNN will be interpreted as octal val...