Creating a Regex for a telephone number

To tie up this chapter, let's put together a few of these features we just learned about and construct the phone number pattern we used in the previous chapter. To sum it up, we want to be able to match all the following number patterns:

123-123-1234
(123)-123-1234
1231231234

So, first off, we can see that there are optional brackets around the first three numbers (the area code), and we also have optional dashes between the numbers. This is a situation where the question mark character comes in handy. For the numbers themselves, we can use a built-in matcher to specify that they have to be numbers and a strong multiplier to specify exactly how many we need. The only special thing we need to know here is that the parenthesis contains special characters, so we will need to escape them (add a backslash):

/(?d{3})?-?d{3}-?d{4}/g

Note

Parentheses are used to define groups in regular expressions, this is why they are special characters. We will learn about defining groups in Chapter 3, Special Characters.

Testing this regular expression with the test application that we developed in Chapter 1, Getting Started with Regex, and with the examples mentioned at the beginning of this topic will show that the regular expression matches all of the examples:

Creating a Regex for a telephone number
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset