0

I want to match all paths that:

don't start with "/foo-bar/"

or not ends with any extension (.jpg, .gif, etc)

examples:

/foo-bar/aaaa/fff will not match

/foo-bar/aaaa/fff.jpg will not match

/aaa/bbb will match

/aaaa/bbbb.jpg will not match

/bbb.a will not match

this is my regex:

^\/(?!foo-bar\/).*(?!\.).*$

but is not working, why?

thanks!

6
  • 1
    Which test cases does it fail on? Commented Apr 20, 2014 at 12:18
  • agree. "is not working" is not a proper problem description. Commented Apr 20, 2014 at 12:18
  • What regex engine do you use?
    – heijp06
    Commented Apr 20, 2014 at 12:19
  • Could be useful : txt2re.com
    – Maen
    Commented Apr 20, 2014 at 12:19
  • i'm trying with regexr.com and other web-based regex tests and you can test with my examples and my regex, is not working :/
    – fj123x
    Commented Apr 20, 2014 at 12:21

2 Answers 2

1

It is more easy to try to match what you don't want. Example with PHP:

if (!preg_match('~^/foo-bar/|\.[^/]+$~', $url))
    echo 'Valid!';

Your pattern doesn't work because of this part .*(?!\.).*$. The first .* is greedy and will take all the characters of the string until the end, after, to make the end of the pattern to succeed, the regex engine will backtrack one character (the last of the string). (?!\.).*$ will always match this last character if it is not a dot.

If you absolutely need an affirmative pattern, you can use this:

if (preg_match('~^/(?!foo-bar/)(?:[^/]*/)*+[^./]*$~', $url))
    echo 'Valid!';
0

You can try this one, which is a bit simpler and close to what you have tried:

^(?!\/foo-bar)([^\.]+)$

Live Demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.