Python 正则表达式不匹配 http:// [英] Python regex not to match http://
问题描述
我在匹配和替换某些未包含在 http://中的单词时遇到问题
当前正则表达式:
http://.*?\s+
这匹配模式 http://www.egg1.com http://www.egg2.com
我需要一个正则表达式来匹配包含在 http://之外的某些词
示例:
"这是一个示例.http://www.egg1.com 和 http://egg2.com.这个正则表达式只会匹配这个egg1和egg2而不是包含在http://中的其他"匹配:egg1egg2已替换:已替换 1 已替换 2
最终输出:
"这是一个示例.http://www.egg1.com 和 http://egg2.com.这个正则表达式只会匹配这个被替换的 1 和被替换的 2 而不是包含在 http://中的其他内容
问题:需要匹配某些模式(例如:egg1 egg2),除非它们是 http://的一部分.如果它们出现在 http://中,则不要匹配 egg1 和 egg2
我能想到的一个解决方案是为 HTTP-URL 和你的模式形成一个组合模式,然后相应地过滤匹配:
导入重新t = "http://www.egg1.com http://egg2.com egg3 egg4"p = re.compile('(http://\S+)|(egg\d)')对于 url,p.findall(t) 中的鸡蛋:如果鸡蛋:打印鸡蛋
印刷品:
<前>蛋3蛋4<小时>
更新:要将这个习语与 re.sub()
一起使用,只需提供一个过滤器函数:
p = re.compile(r'(http://\S+)|(egg(\d+))')def repl(匹配):如果 match.group(2):返回垃圾邮件{0}".format(match.group(3))返回 match.group(0)打印 p.sub(repl, t)
印刷品:
<前>http://www.egg1.com http://egg2.com spam3 spam4I am facing a problem to match and replace certain words, not contained in http://
Present Regex:
http://.*?\s+
This matches the pattern http://www.egg1.com http://www.egg2.com
I need a regex to match certain words contained outside the 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
Final Output :
"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:// "
QUESTION: Need to match certain patterns (as in example : egg1 egg2) unless they are part of http:// .Do not match egg1 and egg2 if they are present within http://
One solution I can think of is to form a combined pattern for HTTP-URLs and your pattern, then filter the matches accordingly:
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: To use this idiom with re.sub()
, just supply a filter function:
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
这篇关于Python 正则表达式不匹配 http://的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!