在Python中使用正则表达式加函数进行编码和替换
我正在尝试在Python中替换字符串,但遇到了一些问题。以下是我想要做的事情。
对于我发布的某条评论:
"here are some great sites that i will do cool things with! https://stackoverflow.com/it's a pig & http://google.com"
我想用Python把字符串变成这样:
"here are some great sites that i will do cool things with! <a href="http://stackoverflow.com">http%3A//stackoverflow.com</a> & <a href="http://google.com">http%3A//google.com</a>
这是我目前的进展...
import re
import urllib
def getExpandedURL(url)
encoded_url = urllib.quote(url)
return "<a href=\"<a href="+url+"\">"+encoded_url+"</a>"
text = '<text from above>'
url_pattern = re.compile('(http.+?[^ ]+', re.I | re.S | re.M)
url_iterator = url_pattern.finditer(text)
for matched_url in url_iterator:
getExpandedURL(matched_url.groups(1)[0])
但我在这里遇到了瓶颈。我之前在这里看到过类似的内容,比如这个:正则表达式但用于匹配写入,但肯定有比逐个匹配然后替换更好的方法。这里的难点在于,这不是简单的替换,而是我需要在替换之前对每个匹配项做一些特定的处理。
1 个回答
3
我觉得你想用 url_pattern.sub(getExpandedURL, text)
这个方法。
re.sub(pattern, repl, string, count=0)
这个方法会返回一个新字符串,它是通过把字符串中最左边不重叠的匹配模式替换成你指定的内容来得到的。这里的 repl 可以是一个字符串,也可以是一个可调用的函数;如果是函数,它会接收一个匹配对象,并且必须返回一个用来替换的字符串。