In a regular expression, ? makes the element immediately before it optional: that element may occur zero or one time. Group the element first when several characters belong together. section 16.4
Use the optional quantifier to accommodate small format variations:
- Add (\d{3}-)? to allow a phone number to include an area code or omit it. section 16.4
- Add ( [-a-zA-Z]+)? to allow a record to include a middle name or initial. section 16.4
- Use {3} when expressing a fixed three-digit repetition inside an optional group. section 16.4
Optional area code
The pattern (\d{3}-)?\d{3}-\d{4} matches both 555-123-4567 and 123-555-123-4567. The question mark applies to the entire grouped area-code sequence. section 16.4
(\d\d\d-)?\d\d\d-\d\d\d\d
Compare a required phone-number prefix with the same prefix made optional by grouping it and adding ?. section 16.4
