0

我有一个形式为:

"Hello, this is a test. Let's tag @[William Maness], and then tag @[Another name], along with @[More Name]."

我想把它转换成...

"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 [...]"

我很确定这可以用正则表达式来完成,但它对我来说有点太复杂了。任何帮助表示赞赏。

4

3 回答 3

2

您可以将任何这样的名称与:

r'@\[([^]]+)\]'

捕获组将原始文本中括号内的名称包围起来。

然后,您可以使用传递给的函数来sub()用链接替换名称,基于您拥有的查找:

def replaceReference(match):
    name = match.group(1)
    return '<a href="/search/%s">%s</a>' % (name.lower().replace(' ', '-'), name)

refs = re.compile(r'@\[([^]]+)\]')
refs.sub(replaceReference, example)

该函数为找到的每个匹配项传递一个匹配对象;使用 检索捕获组.groups(1)

在此示例中,名称以一种非常简单的方式进行转换,但是您可以进行实际的数据库检查,例如,名称是否存在。

演示:

>>> refs.sub(replaceReference, example)
'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>.'
于 2012-10-26T20:27:36.320 回答
2

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>.'
于 2012-10-26T20:29:57.387 回答
0

使用@Martijn 的正则表达式:

>>> s
"Hello, this is a test. Let's tag @[William Maness], and then tag @[Another name], along with @[More Name]."
>>> re.sub(r'@\[([^]]+)\]', r'<a href="/search/\1</a>', s)
'Hello, this is a test. Let\'s tag <a href="/search/William Maness</a>, and then tag <a href="/search/Another name</a>, along with <a href="/search/More Name</a>.'

不过,您需要 slgiy 您的用户名。

于 2012-10-26T20:32:54.623 回答