Book Image

Javascript Regular Expressions

Book Image

Javascript Regular Expressions

Overview of this book

Table of Contents (13 chapters)

Defining ranges in Regex


Ranges in Regex allow you to create your own custom constraints, much like the ones we just went through. In a range, you can specify exactly the characters that can be used or if it's faster, you can specify the inverse, that is, the characters that do not match.

For the sake of illustration, let's say we wanted to match only abc. In this case, we could create a range similar to [abc] and it will match a single character, which is either a, b, or c. Let's test it out with the bicycle text and the /[abc]/g pattern:

Defining a range

Now, this will work, however, if you have a lot of characters you need to match, your range will become long quickly. Luckily, Regex allows you to use the (-) dash character to specify a set of characters without needing to list them out. For example, let's say we want to check whether a three lettered name is formatted correctly, and we want the first letter to be a capital letter, followed by two lower case letters. Instead of specifying...