A regular expression can easily check whether a user entered something that looks like a valid phone number. Thus, the sequences that enclose the first group of digits match literal parenthesis characters.By using capturing groups to remember each set of digits, the same regular expression can be used to replace the subject text with precisely the format you want. Both are followed by a question mark, which makes them optional. This is a textbook example of where we need a backslash to escape a special character so the regular expression treats it as literal input. As we’ve repeatedly seen, parentheses are special characters in regular expressions, but in this case we want to allow a user to enter parentheses and have our regex recognize them.
Any quantifier that allows something to match zero times effectively makes that element optional.This is important because there is no word boundary to be matched between two nonword characters, such as the opening parenthesis and a preceding space character.The first word boundary is relevant only when matching a number without parentheses, since the word boundary always matches between the opening parenthesis and the first digit of a phone number..Another reason to use a noncapturing group here is to allow you to keep using the same replacement string as in the previous examples.If we added a capturing group, we’d have to change . Recipe 2.21 explains how to insert text matched by capturing groups into the replacement text.The first group can optionally be enclosed with parentheses, and the first two groups can optionally be followed with a choice of three separators (a hyphen, dot, or space). ( # Capture the enclosed match to backreference 1: [0-9] # Match a digit # exactly three times. In this case, backreferences to the captured values are used in the replacement text so we can easily reformat the phone number as needed.