RegEx Series: Using Ranges to Find Matches
In my last blog post, I showed how you could use character sets in order to find matches. In this blog post, I am going to build off of that and introduce to you the effectiveness of ranges. Ranges are a great thing in regular expressions, as you will see when we are looking at a consecutive group of letters or numbers for example. Let’s get into the post!
We will be using my favorite resource for regular expressions regex101.com to display the work.
We will use the test string ‘Lets test this string.’
In order to use your range, you will have to put it inside of the character set just as I showed in the last post.
I have put a range inside of my character set. I want to look for any letter that ranges from A-Z as the first character in the regex pattern. The great thing about being able to use a range in this way is that rather than having to manually write out ‘a,b,c,d,e,f….’, we can instead just write A-Z or if you are looking for lowercase, a-z.
If you are using the
i flag, then it won't matter whether you use A-Z or a-z as it will match for both. However, if you don't want to use the i flag, what you can do is put
/[A-Za-z]/g and this will match both ranges of uppercase and lowercase. Your range also does not have to be strictly a through z. It can be a through d (
a-d) or anything else you would like to match for.
As you can see it matches only what is in the range of ‘a’ through ‘e.’
And what we match does not even need to be letters.
We can match number ranges as well, which I find to be the most useful especially when dealing with string because often times you will come across tasks that you will need to deal with numbers as strings such as being asked to remove all zeros and ones from a number. This would be a way you could find those matches for you to remove.
The way we look for numbers is exactly the same as looking for letters.
I have a range of 0 through 9 and it matches the 0 and the 3 I have in my test string.
Or like in the task example I gave you of matching solely 0s and 1s.
Now using the
.match() method and the exclusion method I mentioned in earlier posts, we could extract the 4 4 matches out and ta-da, we have removed the zeros and ones.
This is a great way to use ranges when using regular expressions. Hope that was helpful.