【发布时间】:2017-08-03 04:16:36
【问题描述】:
我希望你能帮助我解决这个问题。我正在用 python 编写代码来替换字符串上的所有匹配项,其中包括:@[username](user:id)
我尝试使用以下代码,但仅在我的字符串是这样的情况下才有效:
mystring = '@[otheruser](id: 100)' and match and replace it's ok. But if I pass a string like this:
mystring = 'He is @[otheruser](id: 100) and he is @[newuser](id: 20)' doesn't work, nothing gets replaced.
代码:
import re
mystring = 'He is @[otheruser](id: 100) and he is @[newuser](id: 20)'
regex = re.compile(r'^@\[([a-zA-Z0-9]+)\]\((id: ([0-9]+))\)', re.S)
iter = re.finditer(regex, mystring)
for result in iter:
match = result.group()
g1 = result.group(1)
g2 = result.group(2)
g3 = result.group(3)
print(match) # full match
print(g1) # otheruser
print(g2) # id: number_id
print(g3) # number_id
parsed_string = re.sub(p, '<a href="view/'+g3+'">@'+g1+'</a>' , mystring)
输出应该类似于:
He is <a href="view/100">@otheruser</a> and he is <a href="view/20">@newuser</a> doesn't work, nothing gets replaced.
【问题讨论】:
-
这个是markdown语法吗?