Regex excluding strings in between two slashes on URL

I have a regex like this basename/(.+)/(.+)/(.+)/?$ but the problem is this is a greedy regex.
I want to exclude certain strings on the 2nd match such that if it matches one of the blacklisted strings, it will return false..

This problem is connected to my other question on https://wordpress.stackexchange.com/questions/102246/wordpress-returns-404-on-custom-rewrite-rules
the only diffence is the approach.

Read More

Hope you guys can help me. Thanks!

EDIT: here is what im trying to work from: basename/(.+)/!(string1|string2|string3).*/(.+)/?$ (added from comments)

P.S. I’ve seen this but this doesn’t seem like what I wanted.

Related posts

Leave a Reply

3 comments

  1. My first if/else regex condition, cool right 🙂 ?
    basename/(.+)/(?(?=(?:bar|string2|string3)/)^|(.+))/(.+)/?$

    So what does this mean ?

    • basename/ : match basename/
    • (.+)/ : anything until / found and match /
    • (?(?=(?:bar|string2|string3)/)^|(.+)) : the tricky part, we’ll split this up:
      • (? : This means if
      • (?=(?:bar|string2|string3)/) : positive lookahead, check if there is bar/ or string2/, or string3/.
      • ^ : If the lookahead succeeded, then match this. ^ means begin of line, since we are in the middle of a string, this will always return false !
      • |(.+) : Else, match everything until …
      • To sum it up, we check if there is bar/ or string2/ or string3/, if there is a match then we’ll look for begin of line ^ which will always return false (our intention) else match further (.*)
    • /(.+)/?$ : match /, then anything until / optionally. $ means end of line.

    Online demo

  2. You’ll want to make catch group that has the same pattern (/dir) lazy matches (using ?).

    For strings such as:

    basename/dir1/dir2/dir3/
    basename/dir1/string1/dir3/  
    basename/dir1/string2/dir3/
    

    The following Regex would return false for the second two but catch the first:

    basename/(.+?)/(?!string1|string2|string3)(.+?)/(.+?)/$
    

    PHP fiddle: http://phpfiddle.org/lite/code/1qr-iip

  3. you could use .*? instead of .* to make it ungreedy, but you’d probably be better with a greedy match that excludes /. ie [^/]*.

    Your question is not all that clear. I’m not sure what you’re doing with the !(x|y|z) construct. That ! is a literal. Is that what you intended?