网址1:/dir-images/no1/top-left.gif
网址2:/test-1/test-2/test
如果它是图像文件(url1),我想匹配最后一个斜杠之前的路径,/dir-images/no1/
如果不是(url2),则匹配整个路径,/test-1/test-2/test
试过^([\=\/\.\w-]+\/)+
这个可以在最后一个斜杠之前得到路径,不管它后面是什么..
尝试:
^([\=/.\w-]+/)+((?!.*\.gif$).*|)
带有的部分(?!)
是前瞻。这有点像 if 语句。有两种不同的前瞻,?=
和?!
。第一个是正常的如果,第二个是“如果不是”。
就你而言,我只是问结局是否不是gif
?然后我匹配一切。
一种方式(有perl
味道):
m|\A(.*/(?(?!.*\.gif$).*))|
解释:
m| ... | # Regexp.
\A # Begin of line.
( # Group 1.
.*/ # All characters until last slash.
(? # Conditional expression.
(?!.*\.gif$) # If line doesn't end with '.gif', match...
.*) # ... until end of line.
)
测试...
内容script.pl
:
use warnings;
use strict;
while ( <DATA> ) {
printf qq[%s\n], $1 if m|\A(.*/(?(?!.*\.gif$).*))|;
}
__DATA__
/dir-images/no1/top-left.gif
/test-1/test-2/test
像这样运行它:
perl script.pl
结果如下:
/dir-images/no1/
/test-1/test-2/test