[英]Python / Regular Expression Token conversion with parameter capture
我有以下形式的字符串:
"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 [...]"
我相當確定這可以使用正則表達式來完成,但是對我來說太復雜了。 任何幫助表示贊賞。
您可以將任何這樣的名稱與:
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>.'
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>.'
使用@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>.'
但是,您需要使用用戶名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.