如何在python中通过重模块查找和替换特殊的url patern(标记语法到HTML)

2024-09-29 23:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,我想搜索这个字符串,以找到包含URL及其名称的特殊模式,然后我需要更改它的格式:

输入字符串:

'Thsi is my [site](http://example.com/url) you can watch it.'

输出字符串:

^{pr2}$

字符串可能有几个url,我需要更改每个url的格式,site是unicode格式,可以是任何语言中的每个字符。在

应该使用什么样的模式?我该怎么做?在


Tags: 字符串名称comyouhttpurlisexample
2条回答

这应该有帮助

import re
A = 'Thsi is my [site](http://example.com/url) you can watch it.'

site = re.compile( "\[(.*)\]" ).search(A).group(1)
url = re.compile( "\((.*)\)" ).search(A).group(1)

print A.replace("[{0}]".format(site), "").replace("({0})".format(url), '<a href="{0}">{1}</a>'.format(url, site))

输出:

^{pr2}$

根据请求在评论中更新:

s = 'my [site](site.com) is about programing (python language)'
site, url =  s[s.find("[")+1:s.find(")")].split("](")
print s.replace("[{0}]".format(site), "").replace("({0})".format(url), '<a href="{0}">{1}</a>'.format(url, site))

输出:

my <a href="site.com">site</a> is about programing (python language)

我不是一个降价专家,但如果这确实是您试图替换的markdown,而不是您自己的语法,那么您应该使用适当的解析器。请注意,如果您将字符串直接粘贴到stackoverflow中(它也使用markdown),它将被转换为一个链接,因此它显然是有效的markdown。在

但是,如果它确实是您自己的格式,请尝试下面的转换

'This is my [site](http://example.com/url) you can watch it.'

进入

^{pr2}$

使用以下匹配项:

\[(.*?)\]\((.*?)\)

以及以下替换regex:

<a href="\\2">\\1<\/a>

在python中,re.sub(match, replace, stringThatYouWantToReplaceStuffIn)应该能做到这一点。不要忘记将re.sub的返回值赋给任何应该包含新字符串的变量。在

相关问题 更多 >

    热门问题