2013-03-27 270 views
0

我试图用正则表达式匹配一些表达式,但它不起作用。我想匹配一个不以http://www.domain.com开头的字符串。这是我的正则表达式:除正确匹配的特定域名之外的URL正则表达式

^https?:\/\/(www\.)?(?!domain\.com) 

是否有我的正则表达式的问题?

我想匹配的表达以http://但不同于http://site.com 例如:

/page.html => false 
http://www.google.fr => true 
http://site.com => false 
http://site.com/page.html => false 
+2

''^字符以外类意味着 “行的开始”,而不是 “不”。 – geoffspear 2013-03-27 15:47:33

+0

你可以发表一个你期望/不匹配的例子,但是没有?正则表达式看起来是合理的。也没有必要转义'/'。 – FatalError 2013-03-27 15:49:23

回答

6

使用此匹配不具有你所提到的域名的URL:在行动https?://(?!(www\.domain\.com\/?)).*

例子:http://regexr.com?34a7p

+0

感谢此解决方案正在工作 – guillaume 2013-03-27 16:06:36

+0

@guillaume - 没问题。 – Daedalus 2013-03-27 16:07:07

0

你要负先行断言:

^https?://(?!(?:www\.)?site\.com).+ 

其中给出:

>>> testdata = '''\ 
... /page.html => false 
... http://www.google.fr => true 
... http://site.com => false 
... http://site.com/page.html => false 
... '''.splitlines() 
>>> not_site_com = re.compile(r'^https?://(?!(?:www\.)?site\.com).+') 
>>> for line in testdata: 
...  match = not_site_com.search(line) 
...  if match: print match.group() 
... 
http://www.google.fr => true 

请注意,该模式不包括www.site.comsite.com

>>> not_site_com.search('https://www.site.com') 
>>> not_site_com.search('https://site.com') 
>>> not_site_com.search('https://site-different.com') 
<_sre.SRE_Match object at 0x10a548510> 
+0

Oups,我忘了一些细节,我编辑我的第一篇文章 – guillaume 2013-03-27 15:57:38

+0

@guillaume:对,那么你仍然需要一个负面的预见断言。 – 2013-03-27 16:08:12

1

这里的问题是,当正则表达式引擎遇到负面前瞻中的成功匹配,它会将比赛视为失败(如预期的那样),并回溯到量化为可选的前一组(www\.),然后查看该表达是否成功没有它。这是你看过的。

这可以通过应用原子分组或占有量词来修复,以“忘记”回溯的可能性。不幸的是python正则表达式不支持本地。相反,您必须使用效率更低的方法:使用更大的预见。

^https?:\/\/(?!(www\.)?(domain\.com)) 
+0

+1,但为什么在前瞻中包含“https?://”? – FatalError 2013-03-27 16:08:48

+0

OP仍然需要匹配以“http://”或“https://”开头的行,只是* not *与域名。 – 2013-03-27 16:09:57

+0

好点,虽然它不应该对表达式的整体结果产生影响,但它可能会使效率下降得更少。我改变了答案来反映这一点。 – JonM 2013-03-27 16:16:50