In my previous blog post, I mentioned some of the ways in which regular expressions can be very useful. I want to continue on the series by giving some great ways to actually start writing our patterns to match in strings. One resource that I think is extremely helpful is regex101.com.
Now, let's start by understanding how to write your regular expression. The pattern that you want to match or test for in your string you will first write it within two forward slashes:
/ insert pattern in here / (optional flags here)
The pattern that you want to put inside of the two slashes can be a literal string, meaning if you want to search for the word “Dog” in the sentence “The Big Brown Dog Jumped Over The Fox” then we can put the word “Dog” inside the slashes.
Flags are used as modifiers to match patterns. We can use flags to match all occurrences or to match patterns regardless of case sensitivity.
I have edited our sentences above slightly just so that I could introduce flags in this post.
I added a second “Dog” into the sentence at the end and yet, it is not matching it.
However, we will add the ‘g’ flag at the end of our regex.
Now it will look for more than 1 match. The ‘g’ flag or the “global” flag will match all of the instances of our regex pattern that are in the string. If I were to continue to write “Dog” 5 more times, then it would match all of those patterns.
I mentioned that regex is case sensitive. Again I have changed the sentence slightly by changing the case of the word dog in our test string.
Here you can see that now, nothing is being matched since the sentence contains “dog” in lowercase, but we can fix this using the insensitive flag.
*you can chain flags
Now it works perfectly because it will look for the pattern regardless of if the pattern is lowercase or uppercase. As you can see, the first instance of “dog” is all uppercase in the test string and all lowercase at the end of the test string and our regex pattern still matches them.
This is how we can match literal patterns using regex.