2012-01-24 162 views
3

我需要它匹配的正则表达式匹配单词正则表达式的URL

http://example.com/foobar 

使用http://example.com/foo/?三种类型相匹配,但它匹配/foobar过我,我不不想要。我应该添加到正则表达式不匹配/foobar

回答

4

试试这个:

^http://example\.com/foo(?:/.*)?$ 
+0

标记为答案。 FlopCoder的解决方案也适用,但我更喜欢这个。谢谢你的帮助! –

+0

@gergoerdosi:不客气。 – Toto

1

在你的正则表达式中,最后的/?表示最后的可选/。所以/foobar也匹配。 试试这个:

http:\/\/example\.com\/foo($|\/.*) 
+0

HTTP:\/\ /例如\ .COM \ /富\ /.*可能是更好的选择。 – synthesizerpatel

+1

Argh。斜斜综合征! –

+0

这不符合第一个例子。 – Toto

0

尝试是这样的:

http://example.com/foo(?:\/|/(\w+)|) 

在正则表达式的形式:

/http:\/\/example.com\/foo(?:\/|\/(\w+)|)/ 

这将example.com/foo匹配或example.com/foo/bar或example.com/foo/


一些交代:

  • (foo|bar)匹配foo或棒
  • (?:)?:的基团,开始将不被捕获
  • \/将匹配/结尾
  • \/(\w+)匹配一个/用一个单词字符重复一次或多次
  • |)在字符串末尾不会匹配任何内容。
+0

也许这只是我,但无法得到这个工作。它仍然匹配/ foobar。 FlopCoder的解决方案有效。非常感谢您的帮助。 –

0

我会用这个负先行(?!):

$urls = array(
    'http://example.com/foo', 
    'http://example.com/foo/', 
    'http://example.com/foo/bar', 
    'http://example.com/foobar' 
); 

foreach ($urls as $url) { 
    if (preg_match('#^http://example\.com/foo(?!bar)#', $url)) { 
     echo $url, " matches.\n"; 
    } else { 
     echo $url, " does NOT match.\n"; 
    } 
} 

// Output: 
// http://example.com/foo matches. 
// http://example.com/foo/ matches. 
// http://example.com/foo/bar matches. 
// http://example.com/foobar does NOT match. 
+0

我认为一般他不想匹配'/ foobar','/ food','/ foo-fighters'。你不会提前知道你想避免匹配什么。 – Tenner

+0

确切地说,/ foobar只是一个例子。 –

+0

@泰纳:啊,好吧,我的错。我认为,如果它没有前面的斜线,他只是试图不匹配一个特定位置的文本(“酒吧”)。 – FtDRbwLXw6