我面临匹配和替换某些单词的问题,这些单词未包含在 http:// 中
当前正则表达式:
http://.*?\s+
这符合模式http://www.egg1.com http://www.egg2.com http://www.egg2.com
我需要一个正则表达式来匹配 http:// 之外包含的某些单词
Example:
"This is a sample. http://www.egg1.com and http://egg2.com. This regex will only match
this egg1 and egg2 and not the others contained inside http:// "
Match: egg1 egg2
Replaced: replaced1 replaced2
最终输出:
"This is a sample. http://www.egg1.com and http://egg2.com. This regex will only
match this replaced1 and replaced2 and not the others contained inside http:// "
问题:
需要匹配某些模式(例如:egg1 Egg2),除非它们是 http:// 的一部分。如果 Egg1 和 Egg2 出现在 http:// 中,则不要匹配它们
我能想到的一种解决方案是为 HTTP-URL 和您的模式形成一个组合模式,然后相应地过滤匹配项:
import re
t = "http://www.egg1.com http://egg2.com egg3 egg4"
p = re.compile('(http://\S+)|(egg\d)')
for url, egg in p.findall(t):
if egg:
print egg
prints:
egg3
egg4
UPDATE:使用这个习语re.sub()
,只需提供一个过滤函数:
p = re.compile(r'(http://\S+)|(egg(\d+))')
def repl(match):
if match.group(2):
return 'spam{0}'.format(match.group(3))
return match.group(0)
print p.sub(repl, t)
prints:
http://www.egg1.com http://egg2.com spam3 spam4
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)