How to know what re.sub took?
darrell at dorb.com
Wed Apr 12 23:20:49 CEST 2000
> How to know what has been substituted away, if one does something like:
> >>> import re
> >>> rex = re.compile(r"(hans|fred|simon)")
> >>> st = "max hans bill"
> >>> st2 = rex.sub("",st)
> >>> st2
> 'max bill'
> It took "hans" away, but how can I learn this automatically?
This won't work for stuff like \g<1> in the replacement string.
def sub(pat, repl, string):
def detect(mo, repl=repl, areas=areas):
return re.sub(pat, detect, string), areas
print sub(r"(hans|fred|simon)","","max hans bill")
('max bill', [('hans',)])
More information about the Python-list