2

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..

Birei
  • 35,723
  • 2
  • 77
  • 82
FEi.TH
  • 91
  • 1
  • 6

2 Answers2

2

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.

Dave Halter
  • 15,556
  • 13
  • 76
  • 103
  • Thanks! My question is if the ending is .gif, does it match the path before last slash? coz in my regex tool, it will not match anything. – FEi.TH Mar 27 '12 at 19:17
  • @user1296363 you only want to know if the whole thing ends with .gif? then just try '\.gif$' – Dave Halter Mar 27 '12 at 19:22
  • @ruakh I don't get the first part. I just fixed the other problem with a pipe, I totally forgot that. – Dave Halter Mar 27 '12 at 19:24
0

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
Birei
  • 35,723
  • 2
  • 77
  • 82