我需要它匹配的正则表达式匹配单词正则表达式的URL
http://example.com/foobar
使用http://example.com/foo/?
三种类型相匹配,但它匹配/foobar
过我,我不不想要。我应该添加到正则表达式不匹配/foobar
?
我需要它匹配的正则表达式匹配单词正则表达式的URL
http://example.com/foobar
使用http://example.com/foo/?
三种类型相匹配,但它匹配/foobar
过我,我不不想要。我应该添加到正则表达式不匹配/foobar
?
试试这个:
^http://example\.com/foo(?:/.*)?$
在你的正则表达式中,最后的/?
表示最后的可选/
。所以/foobar
也匹配。 试试这个:
http:\/\/example\.com\/foo($|\/.*)
尝试是这样的:
http://example.com/foo(?:\/|/(\w+)|)
在正则表达式的形式:
/http:\/\/example.com\/foo(?:\/|\/(\w+)|)/
这将example.com/foo匹配或example.com/foo/bar或example.com/foo/
一些交代:
(foo|bar)
匹配foo或棒(?:)
与?:
的基团,开始将不被捕获\/
将匹配/结尾\/(\w+)
匹配一个/用一个单词字符重复一次或多次|)
在字符串末尾不会匹配任何内容。也许这只是我,但无法得到这个工作。它仍然匹配/ foobar。 FlopCoder的解决方案有效。非常感谢您的帮助。 –
我会用这个负先行(?!
):
$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.
我认为一般他不想匹配'/ foobar','/ food','/ foo-fighters'。你不会提前知道你想避免匹配什么。 – Tenner
确切地说,/ foobar只是一个例子。 –
@泰纳:啊,好吧,我的错。我认为,如果它没有前面的斜线,他只是试图不匹配一个特定位置的文本(“酒吧”)。 – FtDRbwLXw6
JavaScript正则表达式
的https://(例如.COM)/?/ [^ /] * /?(巴)?
测试在这里:(更多信息..)
这个问题在1月份被问到我不确定gergo是否仍在等待答案 – ErrorNotFoundException
标记为答案。 FlopCoder的解决方案也适用,但我更喜欢这个。谢谢你的帮助! –
@gergoerdosi:不客气。 – Toto