Using sub re groups as arguments in functions

Published: Wednesday, Dec 26, 2007 Last modified: Monday, Apr 8, 2024

Read this carefully:

Especially about “dashrepl(matchobj)”.

Sub is definately one of those most useful ways to employ regular expressions. The dashrepl method described lets you play around with group matches as arguments. Very very useful. For example:

result = re.sub(r'\[(' +
		 fileurlpattern + '|' +
		 mailurlpattern + '|' +
		 newsurlpattern + ')\ (.+?)\]',
		 r'<a href="\1">\2</a>', result)

Focusing on last line. I wanted to use \2 as an argument in a function, like so:

r'<a href="\1">thumbgen(\2)</a>', result)

But of course it would never work, due to bad syntax. This is the correct syntax:

thumb.thumburl, result)

and in :

def thumburl(matchobj):
 print # print all groups
 thumbgen( # use that second group