I have a list of URLs and I want to match them in certain conditions:

/blog/article/1 /blog/articles /blog /admin/blog/articles

I'd like to match these URLs using so with the following routing requirements:

To do this you use two characters, the '^' (caret) and '$' (dollar) to wrap the regex and anchor it at the front and back. You can also use them separately to anchor to just one side.

^/blog/article/[0-9]$
^/blog/articles$
^/blog$
^/admin
/blog/article/[0-9]
/blog/articles
/blog
/admin

In the above I have the same 4 regex listed twice, but the first 4 has the anchors added to them so that they only match completely.

What You Should See

When you run this you can see the effect of the anchors:

That file doesn't exist.
> ^/blog/article/[0-9]$
Input file is empty. Use !load to load something.
> ^/blog/articles$
Input file is empty. Use !load to load something.
> ^/blog$
Input file is empty. Use !load to load something.
> ^/admin
Input file is empty. Use !load to load something.
> /blog/article/[0-9]
Input file is empty. Use !load to load something.
> /blog/articles
Input file is empty. Use !load to load something.
> /blog
Input file is empty. Use !load to load something.
> /admin
Input file is empty. Use !load to load something.
>

You can see that the first set works exactly as expected with each regex matching one URL. The second set with out the anchors seems to match all the wrong things because it's finding the element anywhere in the path.

Extra Credit

  • This exercise might have flown past you because it is subtle, so take the time to manually enter each of these regex into the Regetron shell and see what URLs they match.
  • Rerun this but put !match at the beginning of the script to see if it changes things.
  • Add some more URLs and use anchors to match them as well.
  • What happens when you have a URL for article 10? Why does this fail?
  • Go reasearch the routing engine of a web framework you're familiar with and see how they might use anchors or not.

Portability Notes

Depending on the engine you use this could be a speed improvement or not. Also some platforms default to this behavior by default, but others do kind of a half-way version of this.