This matches all of your demo data and also matches only numbers, such as 18001234321
\+?1?\D*\d\d\d\D*\d\d\d\D*\d\d\d\d\b
You can also see its technical description at the bottom of this page: http://regex101.com/r/lE2fR2
Basically, its zero-or-more non-digits (\D
) followed by some digits (\d
).
For 800 numbers, just change the first \d
to an 8
.
If your goal is to strip out everything but the numbers, then capture the numbers and replace with the capture groups:
Find what: \+?(1?)\D*(\d\d\d)\D*(\d\d\d)\D*(\d\d\d\d)\b
Replace with: $1$2$3$4
Java:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
<P>{@code java StripPhoneFormattingXmpl}</P>
**/
public class StripPhoneFormattingXmpl {
public static final void main(String[] igno_red) {
String sToSearch = "1(800) 765-4321 1 877 765-4321 1-855-765-4321 1.800.765.4321 18001231234";
String sRegex = "\\+?(1?)\\D*(\\d\\d\\d)\\D*(\\d\\d\\d)\\D*(\\d\\d\\d\\d)\\b";
String sRplcWith = "$1$2$3$4";
Matcher m = Pattern.compile(sRegex).matcher(sToSearch);
StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, sRplcWith);
}
m.appendTail(sb);
System.out.println("Original: " + sToSearch);
System.out.println("Stripped: " + sb);
}
}
Output:
[C:\java_code\]java StripPhoneFormattingXmpl
Original: 1(800) 765-4321 1 877 765-4321 1-855-765-4321 1.800.765.4321 18001231234
Stripped: 18007654321 18777654321 18557654321 18007654321 18001231234