thi*_*ool 6 python regex regex-negation
我正面临一个问题,要匹配并替换某些单词,不包含在http://中
目前的正则表达式:
http://.*?\s+
Run Code Online (Sandbox Code Playgroud)
这符合模式 http://www.egg1.com http://www.egg2.com
我需要一个正则表达式来匹配http://之外的某些单词
例:
"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
Run Code Online (Sandbox Code Playgroud)
最终产出:
"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:// "
Run Code Online (Sandbox Code Playgroud)
问题:需要匹配某些模式(例如:egg1 egg2),除非它们是http://的一部分.如果它们存在于http://中,则不匹配egg1和egg2
我能想到的一个解决方案是为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
Run Code Online (Sandbox Code Playgroud)
打印:
egg3 egg4
更新:要使用此习语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)
Run Code Online (Sandbox Code Playgroud)
打印:
http://www.egg1.com http://egg2.com spam3 spam4