views:

74

answers:

3

I'm working on some routes for my CodeIgniter application, and I need to declare a 'catch-all'/except one regular expression. Any route that doesn't start with 'ajax/' should be redirected to the 'main'-router. Like so:

$route['regexmagichere'] = "main";

So this is definetly way beyond my regex skills and I need some help. The regex should return true on all strings that don't start with 'ajax/', like so:

$string_one = "ajax/someotherstuffhere";
$string_two = " ajax/test";
$string_three = "somestuffhere";

Here $string_one would be the only one returning false. Thanks for your time!

+5  A: 

You could try

^((?!ajax).*)
Robusto
From the manual: Note that the apparently similar pattern (?!foo)bar does not find an occurrence of "bar" that is preceded by something other than "foo"; it finds any occurrence of "bar" whatsoever, because the assertion (?!foo) is always TRUE when the next three characters are "bar". A lookbehind assertion is needed to achieve this effect.
Question Mark
@Question Mark - Not true in this case the `^` anchors to the start of the string, then `(?!ajax)` ensures that the first characters are not `"ajax"` proceeding onward to capture the whole string with the `(.*)`
gnarf
There is a difference between `(?!foo)bar` and `(?!foo).*` - this solution will work fine, although the capturing group probably isn't necessary - using `^(?!ajax).*` is fine.
Peter Boughton
A: 

I think ^(?<!ajax)\/ will do the trick.

I stress "think"!

Question Mark
Using a look-behind at the start of the string seems silly... This would match any string starting with `/`
gnarf
the look behind is on the /, and matching /someotherstuffhere satisfies the question's criteria no?
Question Mark
Have you specifically tested this expression on CodeIgniter? Does it include a slash at the start of all paths? Will the slash need escaping?
Peter Boughton
codeignitor uses preg_match using # delimiters, so no, the slash doesn't need escaping, my bad, can't hurt though. There is no leading slash so this expression would never fall for gnarf's comment above.
Question Mark
+2  A: 

To be litereal to your request. A regexp that returns true for all strings that don't start with ajax/:

^(?!ajax/).*

You might need to escape the / as \/. (?!) is a negative look-ahead expression explained on this question.

gnarf
Just wondering, if this is just a boolean match, is the `*` necessary?
Peter Boughton
Likely not... the `.` probably isn't necessary either, but I didn't test, and wasn't aware if codeigntor does anything funky if you don't consume the whole string in the route match...
gnarf