re.sub()
也接受函数,因此您可以处理替换文本:
import re
text = "Hello, this is a test. Let's tag @[William Maness], and then tag @[Another name], along with @[More Name]."
def replace(match):
text = match.group(1) # Extract the first capturing group
return '<a href="/search/{0}">{1}</a>'.format( # Format it into a link
text.lower().replace(' ', '-'),
text
)
re.sub(r'@\[(.*?)\]', replace, text)
或者,如果您正在寻找一个可读的单行:
>>> import re
>>> re.sub(r'@\[(.*?)\]', (lambda m: (lambda x: '<a href="/search/{0}">{1}</a>'.format(x.lower().replace(' ', '-'), x))(m.group(1))), text)
'Hello, this is a test. Let\'s tag <a href="/search/william-maness">William Maness</a>, and then tag <a href="/search/another-name">Another name</a>, along with <a href="/search/more-name">More Name</a>.'