In this lesson, we will see what to do when some characters you want to match are optional, i.e., if they are present, match them and if they are not, don't bother.
So, Imagine a situation where you want to match foo and foobar. Hence,
bar is optional. Then, what do we do to match and identify such words? Let's see ...
We can start with
/foo/. As you see, it matches both foo and *foobar * but also matches any other word that contain foo. So, not exactly what we want.
For situations like these we use '?' which tells the RegEx engine that what ever character that precedes the '?' is optional and is not required.
Now let's simplify the problem a bit. We want to match only foo and foob for now.
So, we'll do
As you see, it matches both foo and foob completely. So, this is good. Although, it still matches food, ignore that for now.
Extending the same idea forwards,
/foob?a?r?/ will mean that 'b', 'a', 'r' are optional. And all of these words foo, foob, fooba and foobar. Since I am looking for only foo and foobar , I need to do something more to not allow the intermediaries.
Also, too many ?'s in the RegEx don't look that good.
So, Let's see how it can be done to meet our requirements. We will use grouping to do that. Groups will be covered in much detail in a separate tutorial. For now just sit tight and continue. So, we will do this,
/foo(bar)?/. And, as you can see it is matching both foo and foobar as we wanted.
Now, let's try to understand what we did here.
(bar) is called a Group. Group is just a fancy way of saying that everything inside has something in common.
And, in our case the common property is that all the letters inside are optional. And, when the RegEx engine looks at that it knows bar is optional and so matches foo even if bar is present or not. The end result being only foo and foobar are matched completely and not the other things.
Now, Its time for some RegExercise...
What will you do to match both 'cats' and 'carts' but nothing else?
Think about it and try it in Regexr.com to see if it is working.
Well, that is everything for this tutorial. Stay Tuned for more.