Sometimes you want to match something optionally, meaning it can be there or not and it will still match. You do this with the '?' (question-mark) character. Simply put it after the regex symbol or set you want to be optional and you'll see it match. Here's a few URLs to try this on:

/blog/article/1 /blog/article/ /blog/article/2

Just a few URLs but imagine you want to match any of those as being the same thing. To do that you just put a '?' at the end and it will optionally match the [0-9] character set. I'm going to write one regex but it's in verbose mode so I can comment on each character and you can see it:

^/blog/article/[0-9]?$

^     # from the start
/blog/article/
[0-9] # any of 0-9
?     # optional though
$     # to the end

First I have the regex like normal, then I wrote it out verbose. Let's walk through how the engine would match the first of our regex:

ex8.regex:3
From the start of /blog/article/1...
ex8.regex:4
match /blog/article/ so that matches. Now we're on the 1 character of the corpus text.
ex8.regex:5
Match a [0-9] set, and 1 is in that set so match.
ex8.regex:6
The last thing is optional because of ? but it matched so this is matched.
ex8.regex:7
Match the end, and since were are out of characters in the corpus text we are done and this matches.

What You Should See

When you run this you should see it match all of these URLs twice, since we have the regex repeated in verbose form for you

That file doesn't exist.
> ^/blog/article/[0-9]?$
Input file is empty. Use !load to load something.
>
^     # from the start
/blog/article/
[0-9] # any of 0-9
?     # optional though
$     # to the end

Input file is empty. Use !load to load something.
>

Extra Credit

  • Use this process I followed and manually match the regex against the other URLs too. If it helps, write the regex on a piece of paper, and write the corpus text (the URL) on another part of the paper. Then underline the parts of the URL that match as you walk through the regex and put you finger on each regex char that matches.
  • Write some URLs that do not match this regex and explain why they don't.
  • Using more ? characters, make more of this regex optional.
  • Add 4 optional digits at the end so that you can match an article numbered 9102.