I've attempted multiple times to write a regex field validator for an asp.net intranet form web form. I've tried to tweek mine with no success. The current one i'm using and attempting to edit is
((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}
I need to be able to allow.
x1245
508-555-1212
5085551212
508 555 1212
508-555-1212 x1234
5085551212 x1243
508 555 1212 x1234
The only one i have covered is the second one on the list is the second one down.
This will do it.
(\d\d\d-?\s?\d\d\d-?\s?\d\d\d\d\s?)?(x\d\d\d\d)?
or shorter equivalent:
(\d{3}-?\s?\d{3}-?\s?\d{4}\s?)?(x\d{4})?
You want to match the full phone number, optionally with space/dash, and make that whole thing optional, then include extension, and make that optional too.
A pattern like this would match all your inputs:
\d{3}[- ]?\d{3}[- ]?\d{4}( x\d{4})?|x\d{4}
This will match either:
an optional group of:
x
—or—
x
Depending on your precise needs, you may need to start (^
) and end ($
) anchors to prohibit extra characters around your pattern (e.g. "foo x1234 bar"
):
^\d{3}[- ]?\d{3}[- ]?\d{4}( x\d{4})?|x\d{4}$
Update
If you'd like to ensure that the digit two separators between the three phone number segments must be the same—e.g. 508-555 1212
would not be allowed—the easiest way would be something like this:
\d{3}([- ]?)\d{3}\1\d{4}( x\d{4})?|x\d{4}
The (...)
creates a capture group, and because it happens to be the first one in the pattern, it's referred to as group 1. The \1
is a backreference, which will only match the exact string which was matched in group 1.
This one quite complicated but will match
var regex = new Regex(@"^(?<number>\d{3}(?<separator>([\s-]|))\d{3}\k<separator>\d{4})?" +
"((?<=\d)\s|(?<=^)|(?=$))" +
"(?<extension>x\d{4})?(?<=.)$");
^
start of string(?<number>
start named group number\d{3}
match 3 digits(?<separator>
start named group separator([\s-]|)
match space, -
or empty string)
close group seperator\d{3}
match 3 digits\k<separator>
match previous separator\d{4}
match 4 digits)
close group number?
previous match is optional((?<=d)\s|(<=^)|(?=$))
previous char is a digit and match space, or match zero length if at start or end of string(?<extension>)
start named group extensionx\d{4}
match x
followed by 4 digits.)
close group extension?
extension group is optional(?<=.)
zero length match that insures string isn't empty$
match end of stringIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With