June 19, 2016

RegEx : The Right Way | Optional Characters?

02:24 Posted by Durga swaroop Perla , , , , No comments
We have already seen how to use the dot operator in Regular Expressions in the last tutorial (Link). To see all the articles of this Regular Expressions series, click here .
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 contains 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 /foob?/
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.
Happy RegExing!

If you have liked this article and would like to see more, subscribe to our Facebook and G+ pages.
Facebook page @ Facebook.com/freblogg
Google Plus Page @ Google.com/freblogg


Post a Comment

Please Enter your comment here......