Regex: match everything before image
Question
url1: /dir-images/no1/top-left.gif
url2: /test-1/test-2/test
I want to match the path before the last slash if it is an image file(url1), aka /dir-images/no1/
and match the whole path if it is not(url2), /test-1/test-2/test
tried ^([\=\/\.\w-]+\/)+
this could get path before the last slash no matter what is after it..
Solution
Try:
^([\=/.\w-]+/)+((?!.*\.gif$).*|)
The part with (?!)
is a lookahead. This is something like an if statement. There are two different lookaheads, ?=
and ?!
. The first one is a normal if, the second one is an 'if not'.
In your case, I just ask if the ending is not gif
? And then I match everything.
OTHER TIPS
One way (with perl
flavour):
m|\A(.*/(?(?!.*\.gif$).*))|
Explanation:
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.
)
Testing...
Content of 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
Run it like:
perl script.pl
And following result:
/dir-images/no1/
/test-1/test-2/test
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow