RegexCraft

US phone number regex

Matches ten-digit North American numbers written as (555) 123-4567, 555.987.6543, 555-234-5678 or 555 234 5678.

Open in the tester

The pattern

/\(?\b\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}\b/g

Sample text, 3 matches

Call Ada at (555) 123-4567 or Grace at 555.987.6543; the desk line is 555 234 5678.

What it deliberately doesn’t do

  • Country codes (+1) and extensions (x204) are not part of the match.
  • It checks the shape, not the numbering plan: area codes starting with 0 or 1 still match.

Explained, in order

  1. \(Matches the character '(' literally
  2. ?The preceding element matches optionally (zero or one time) (greedy)
  3. \bWord boundary — asserts a boundary between a word character and a non-word character. Consumes no characters.
  4. \dMatches a digit (0–9)
  5. {3}The preceding element matches exactly 3 times (greedy)
  6. \)Matches the character ')' literally
  7. ?The preceding element matches optionally (zero or one time) (greedy)
  8. [-. ]Character class — matches one character from: '-', '.', ' ' (space)
  9. ?The preceding element matches optionally (zero or one time) (greedy)
  10. \dMatches a digit (0–9)
  11. {3}The preceding element matches exactly 3 times (greedy)
  12. [-. ]Character class — matches one character from: '-', '.', ' ' (space)
  13. ?The preceding element matches optionally (zero or one time) (greedy)
  14. \dMatches a digit (0–9)
  15. {4}The preceding element matches exactly 4 times (greedy)
  16. \bWord boundary — asserts a boundary between a word character and a non-word character. Consumes no characters.

In your language

JavaScript

The engine this page was tested with.

const re = /\(?\b\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}\b/g;

// Example
const matches = [...str.matchAll(/\(?\b\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}\b/g)];
for (const m of matches) {
  console.log(m[0], m.index, m.groups);
}

Python

Translated. Named groups are rewritten to (?P<name>…).

import re

pattern = re.compile(r"\(?\b\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}\b")

# Example
for m in pattern.finditer(text):
    print(m.group(0), m.start(), m.groups())

Go

Translated. Go's RE2 has no lookaround or backreferences.

package main

import (
	"fmt"
	"regexp"
)

var re = regexp.MustCompile(`\(?\b\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}\b`)

func main() {
	for _, match := range re.FindAllStringSubmatch(text, -1) {
		fmt.Println(match[0], match)
	}
}

Rust

Translated. The regex crate has no lookaround or backreferences.

use regex::Regex;

// Note: Rust finds all matches via find_iter / captures_iter (no 'g' flag).

fn main() {
    let re = Regex::new(r#"\(?\b\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}\b"#).unwrap();

    for m in re.find_iter(text) {
        println!("{} at {}", m.as_str(), m.start());
    }
}