RegEx Series: (Part 2) Special Characters & Quantifiers

Introduction

I promised that in this blog post that I would introduce how to use quantifiers with special and meta characters. The great thing about quantifiers is that you can use them to tell how many times a character should repeat. For example, when I introduced character sets, we might try to match a pattern such as

This would mean that only the first character would be an alphabetical character of ‘a’ through ‘z’ and the next characters would be ‘1’ and ‘1’. However, what if we wanted to match a string where the first four characters were alphabetical followed by our two 1's? We might have to write it out in multiple character sets or we can specify with quantifiers. Let’s look at the picture below.

To add a quantifier after the pattern I am looking for, you add in curly braces {} and inside of those, you can add in the number of times you want to match that pattern. In this case, I want to match anything that has exactly 4 alphabetical characters before two 1’s in it.

We can get more specific and give it an end condition {start, end}.

This is the same as above, but instead, we are matching patterns that are between 6 and 8 alphabetical characters long before our two 1’s. As you can see the first string is only 4 characters long before the two 1’s, so it doesn't count as a match.

If you repeat the same as above, but don't add in the 8 into the curly braces, it interprets that by looking for matches that are at least 6 characters long and more. If you know that your string will at the very least have ‘x’ number of the pattern you need, then you can use that strategy.

Another way, we can try to quantify a match if you don't necessarily need to be specific on the number or the range is with the . The sign means match the pattern exactly one or more times. I will show you an example:

With the sign, it will match the original test string that we used with the quantifier, but it will also match whatever amount of alphabetical character comes before two 1’s.

These are two ways to quantify your patterns when using regular expressions. One using the quantifier method, and the other using the special character .

Conclusion

In part 3, and the final part of the special characters installment of this series, I will finish up with the more commonly used special characters such as the wildcard character. See you then!

Software Developer && Political Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store