Not condition in regex in routes

I’m terrible at regex. I use a route that looks like this:

kirby()->routes(array(
  array(
    'pattern' => '(.+)',
    'action'  => function( $uid ) {
      echo $uid;
    }
  ),
));

However it prevent me from for example using plugin assets. Can I use a NOT condition in the regex?

Something like this:

 'pattern' => '(.+)NOT assets*',

Or maybe:

 'pattern' => array('(.+)', '(!assets*)'),

Or something like that? But the above is using OR? I’ll need to use AND NOT.

Not sure if what you’re trying to do is a good idea, but I’m not here to judge :wink:

What you’re looking for is probably the negative lookahead: /^(?!assets)(.*)/

Matches “some/url”, but does not match anything starting with assets like “assets/url”.

I’m aware of the danger of just matching anything. :slight_smile:

I tried your regex. It did not work out of the box in the route, but this seems to work:

'pattern' => '(?!assets)(.*)',

Correct me if it’s wrong.

The reason for why I need it right now is this:

categories
  category1
  category2
pages
  about
  contact

I use parent pages as sections to group the pages, but I still want access to them from the root, like this:

example.com/category1
example.com/about

I just figured out that another way, instead of match all could be to generate some kind of whitelist and put that into the route pattern. That is probably only a good solution if there are not that many pages on the site.

As I said, I’m not here to judge. I’ve seen enough of your posts and plugins to know that you most likely have a good reason for whatever it is you’re doing. Once we get our route filters, everything will be fine :slight_smile:

Your regex looks fine, I’m just never sure off the top of my head what the pattern expression actually matches against - whether it is the full path starting with ‘/’ or not.

1 Like

Off topic, but I’m completely terrible at regex too, and this has been my lifesaver for a few months : https://simple-regex.com/

2 Likes

For Mac users, I’ve found the RegExRX app to be quite handy for building RegEx strings and testing them.