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.
The pattern
//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
\(Matches the character '(' literally?The preceding element matches optionally (zero or one time) (greedy)\bWord boundary — asserts a boundary between a word character and a non-word character. Consumes no characters.\dMatches a digit (0–9){3}The preceding element matches exactly 3 times (greedy)\)Matches the character ')' literally?The preceding element matches optionally (zero or one time) (greedy)[-. ]Character class — matches one character from: '-', '.', ' ' (space)?The preceding element matches optionally (zero or one time) (greedy)\dMatches a digit (0–9){3}The preceding element matches exactly 3 times (greedy)[-. ]Character class — matches one character from: '-', '.', ' ' (space)?The preceding element matches optionally (zero or one time) (greedy)\dMatches a digit (0–9){4}The preceding element matches exactly 4 times (greedy)\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());
}
}