June 19, 2016

RegEx : The Right Way | Dot Operator

02:18 Posted by Durga swaroop Perla , , , , , , No comments
Let's continue with Regular Expressions. All articles in this series can be found here. I will be using Regexr.com for most of these tutorials. It is a great site, where you can write and validate your regular expressions against your desired input text.
Now, Let's look at how regular expressions usually look like..
The '/' before and after the pattern is the delimiter. We put our search pattern between the delimiters and in the end pass a flag. Flags add a bit more control on what you want to accomplish. So, with that knowledge let's get started.
Matching a String
To match any given string, we just do this,  /{string}/ and the Regex engine will find that string from the text.
So, when i search for Blogg it will be matched with FreBlogg as we can expect but not with 'blogg'. This is because by default it is case-sensitive.
To, match even the 'blogg' on the second line, you can use the (ignores the case) flag along with g. But, the problem with that i flag is that it will match a lot more than we want it to.

 As, you see here, it matches a lot of other variations of the word. So, use the flag with caution as it can match other strings you might not want to.
We will later see what to do if you only want to match 'Blogg' and 'blogg' and nothing else.
So, that is how you can match for a single string. Let's look at the Dot operator now.
The Dot Operator
The /./ in regex, matches every character, except the newline characters.
We use this when we want to match a character but don't care what it is. As you see in the image, it matches all characters, numbers and spaces. Even special characters like @,!,$.. will be matched.
Now, when i try with /D./ , it matches Do  because the Dot will match anything. But, it didn't match the 'D' on line 2 with 'o' on line 3, because dot operator won't match new line characters and we have a new line character after 'D'.
So, Let's use the stuff we've learned till now and do a small exercise.
Say, I want to match three letter words, i can use /.../ like this, but look at what it matched.
As you see it did not exactly do what we wanted. Since, Dot matches Spaces as well, it matches a space and two letters as in 'oh'. So, we can't use it for this particular case.  We will see much better way to do the same thing in the later tutorials.
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......