Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的模式匹配与替换_Python_Pattern Matching - Fatal编程技术网

Python中的模式匹配与替换

Python中的模式匹配与替换,python,pattern-matching,Python,Pattern Matching,我正在尝试获取一个字符串,它可以是“Hello here is a[URL]www.URL.com[/URL]and it's great.”并能够提取[URL]和[/URL]之间的任何内容,然后修改字符串,使其现在变成“Hello here is awww.URL.com,it's great.” 所以我想也许我可以做一个string.split(),然后得到[URL]和[/URL]之间的文本,然后做一个string.replace(),用新的部分,但我想知道是否有更简单的解决方案。使用正则表

我正在尝试获取一个字符串,它可以是“Hello here is a[URL]www.URL.com[/URL]and it's great.”并能够提取[URL]和[/URL]之间的任何内容,然后修改字符串,使其现在变成“Hello here is awww.URL.com,it's great.”


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

使用正则表达式:

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.")
重新导入
打印re.sub(r'\[URL\](.*?\[/URL\]',r'',“您好,这里是一个[URL]www.URL.com[/URL],太棒了。”)

使用正则表达式搜索
[URL]somestringhere[\URL]
并保存
somestringhere