OK, that is one long regexp I would work on simplifying it just a bit. I think it is easier to start backwards on this one since you know that a phone number will always end with four digits. You basically have that already:
You don’t need the square brackets here because the only thing you are looking for is digits, so you can simplify that to:
Now is there always going to be a dash before the last four digits? Looking at the instructions the answer is no. There could also be a space, or there could be nothing (the last four digits immediately follow the preceding three digits). So you’ll want to change the \- into something that can take all of these scenarios into account.
Once you get this part working then move on to the three digits in front of the last four and apply the same logic. Then once you have that working you just need the area code, which is slightly more tricky since you have parens to be concerned about. Don’t forget that regular expressions have the equivalent of the OR operator to help you out.
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
Let’s look at the end of your expression. This says to look for three numbers followed by a dash and then four numbers. So this will catch a phone number of the form 123-4567. But you know that valid phone numbers can also end with 123 4567 and 1234567. So you’ll want to fix this part of the expression so that it takes into account that there can be a space instead of a dash, or nothing between the numbers.
You can modify just the part of the expression pasted above to do this. It does not involve using the pipe | to OR things together. Let’s concentrate on just looking for either the dash or a space. Do you know of a way to use a regular expression to look for a single character that can be either one thing or another?
Lets suppose we are only using the dash (b/w the last three and four digits) instead of space so in that case we are bound to use either a dash , a bracket space or only a bracket between the next set of three digits like this :
Similarly, lets suppose we are using space (b/w the last three and four digits) instead of dash then we are bound to use only a space between the next set of three digits like this :
555 555 5555
That is why the regex is lengthy, and I can not incorporate a single character that can be one thing or another as you stated above.