2015-12-16 46 views
1

我觉得我非常接近,我正在写一个部分url的正则表达式。正则表达式 - 部分url

请注意:我的例子显示最多两个/然而它可能有其他或更多。示例/test/test/test.htm

它可以接受a-z 0-9 - 和。如果它有下面引用的文件扩展名之一。它不能以a或a开始/结束。前后必须有数字或字符。目前我正则表达式是接受应拒绝

接受

/test/test.htm (this could be jpeg|jpg|gif|png|htm|html) 
/test/test 
/test/test-test.htm 
/test/test-test 
/test/test123.htm 
/test/test123 

应该被拒绝(但传球)

/test/test. 
/test/.hhh 
/tes t 
/tes_t 
/tes"t 
/tes’t 
/-test (cannot start with any thing else other than letters/numbers 

正则表达式:^\/.*?(\.(jpeg|jpg|gif|png|htm|html)|([^\.])[\w-]{1})$

+1

任何缺少的情况? – CinCout

+0

我认为我想到了一切 –

+1

那么你的问题是什么? – CinCout

回答

3

这是我能找到的最完整的正则表达式。我为其他人的正则表达式添加了一条评论,因为他们在/test/test-(他们的正则表达式会接受)上失败。

^\/[a-zA-Z0-9]+([-\/](?:[a-zA-Z0-9]+))*(\.(?:jpe?g|gif|png|html?))?$ 

请参阅here

Regex explanation

如果您需要匹配结果-以及(如/test--test),你可以使用下面的正则表达式,所看到here

^\/[a-zA-Z0-9]+((?:-+|\/)(?:[a-zA-Z0-9]+))*(\.(?:jpe?g|gif|png|html?))?$ 
+0

@WashingtonGuedes不知道这是OP需要匹配的情况,但我已经为这种情况添加了正则表达式。 –

1

大概可以进行优化:

^(\/[a-zA-Z0-9\d]+)+([a-zA-Z0-9-]*\.(jpeg|jpg|gif|png|htm|html))?$ 

Try it live here

  • 我们像/abd文件夹与\/[a-zA-Z0-9\d]+多的时间,这也包括文件名
  • 第一场比赛模式也允许文件名有他们的名字-
  • 然后任选匹配扩展
+0

对不起,可能我是愚蠢的。/tes't显示为匹配,会通过还是失败? –

+0

Oups,忘了'$'对匹配更加严格。看看我最后的编辑。 – Cyrbil

+0

这将在'/ test/test-'上失败 - 它会匹配。 –

1

试试这个正则表达式:

^(?:\/[a-z0-9](?:[^\/ _"’\n.-]|\.(?=(?:jpe?g|gif|png|html?)$)|\-(?!$))+)+$

Regex live here.

解释:

^(?: # from start \/[a-z0-9] # one slash and one letter or digit (?: # one of: [^\/ _"’\n.-] # characters not in this list | # OR \.(?=(?:jpe?g|gif|png|html?)$) # one dot with the condition # of being the extension dot # at the end | # OR \-(?!$) # one - not at the end )+ # at least one of them to many )+$ # as there could be /folder/folder # as many matches till the end

希望它能帮助。

+0

这会在'/ test/test-'上失败 - 它会匹配。 –