Regular Expression Question!

Hi All,

I’m doing these quizzes I found online so I can get more comfortable with REGEX. This particular problem is asking me to match these phone numbers:

415-555-1234
650-555-2345
  (416)555-3456
1 416 555 9292
4035555678
  202 555 4567

This is the solution:
1?[\s-]?\(?(\d{3})\)?[\s-]?\d{3}[\s-]?\d{4}

I don’t understand what the second backslash before the parentheses is for?
1? - to capture for one
[\s-]? - to capture for dash or white space
\(?(\d{3})\)? - I am asking about this backslash in the beginning to capture the area code.

When I remove it, the code didn’t work.

Will someone help me explain? I understand the rest of it.

Thanks in advance!!

Do you mean the \d symbol? \d is equivalent to [0-9]

Hm i understand why the backslash disappears. Im talking about the backslash before the area code

it is to escape the parenthesis, so it is a literal parenthesis and not the opening parenthesis of a capture group


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.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

ah! I understand now. Thank you so much!

and thank you for editing my post and the tip on back ticks :slight_smile:

1 Like