【问题标题】:Using Regex Plus Function in Python to Encode and Substitute在 Python 中使用 Regex Plus 函数进行编码和替换
【发布时间】:2010-09-22 02:30:56
【问题描述】:

我正在尝试在 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> &amp; <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])

但这就是我卡住的地方。我以前在这里看到过这样的事情:Regular Expressions but for Writing in the Match 但肯定有比遍历每场比赛并对其进行位置替换更好的方法。这里的困难在于它不是直接替换,但我需要在替换之前对每场比赛做一些具体的事情。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    我想你想要url_pattern.sub(getExpandedURL, text)

    re.sub(pattern, repl, string, count=0)

    返回通过替换 repl 替换 string 中模式的最左边不重叠出现而获得的字符串。 repl 可以是字符串或可调用对象;如果是可调用的,则传递匹配对象,并且必须返回要使用的替换字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      相关资源
      最近更新 更多