Python中的模式匹配和替换 [英] Pattern matching and replacing in Python

查看:82
本文介绍了Python中的模式匹配和替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个字符串,它可以是你好,这里是一个 [URL]www.url.com[/URL],它很棒."并能够提取 [URL] 和 [/URL] 之间的任何内容,然后修改字符串,使其现在变为你好,这里是一个 < a href='www.url.com'>www.url.com</a> 很棒."

I'm trying to take a string that can be anything like "Hello here is a [URL]www.url.com[/URL] and it's great." and be able to extract whatever is between [URL] and [/URL] and then modify the string so it now becomes "Hello here is a < a href='www.url.com'>www.url.com< /a> and it's great."

所以我在想也许我可以做一个 string.split() 然后获取 [URL] 和 [/URL] 之间的文本,然后用新的部分做一个 string.replace() 但我想知道是否有一个更简单的解决方案.

So I was thinking maybe I could do a string.split() and then get the text between [URL] and [/URL] and then do a string.replace() with the new part but I wanted to know if there was a simpler solution.

推荐答案

使用正则表达式:

import re
print re.sub(r'\[URL\](.*?)\[/URL\]',r'<a href="\1">\1</a>', "Hello here is a [URL]www.url.com[/URL] and it's great.")

这篇关于Python中的模式匹配和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆