Suppose I have the following 2 strings representing phone numbers:
The first one is for a normal phone number (111) 222-3333
and the second one is for a phone number with an extension (111) 222-3333 ext 4
So we know the phone number will always be 10 digits and possibly 11. If it is 11, then I'd like it formatted with the second version.
My current regex and replace are as follows:
Regex: (\d{3})(\d{3})(\d{4})(\d?)
Replacement: ($1) $2-$3 ext $4
Which works, except that regardless whether the 4th capturing group exists or not, I get the "ext" added in, so I get:
1112223333
> (111) 222-3333 ext
(should be (111) 222-3333
(no "ext" suffix)
11122233334
> (111) 222-3333 ext 4
(correct)
I know I can do this via code / evaluating matches (I'm programming in C# / .Net), but I'm more curious to know if there a way to change the replacement regex itself to have some form of logic to only add the suffix ext $4
if and only if there was a 4th capturing group?
Well, the nearest I could get to this is using the match evaluator overload with C# 6 string interpolation.
Sample using C# 6 string interpolation:
var phone = "01234567894";
var txt = Regex.Replace(
phone,
@"^(\d{3})(\d{3})(\d{4})(\d?)$",
m => $"({m.Groups[1]}) {m.Groups[2]}-{m.Groups[3]}{(m.Groups[4].Success ? " ext " + m.Groups[4].Value : "")}");
Or, if using older C#, using String.Format
:
var phone = "01234567894";
var txt = Regex.Replace(
phone,
@"^(\d{3})(\d{3})(\d{4})(\d?)$",
m => String.Format("({0}) {1}-{2}{3}", m.Groups[1], m.Groups[2], m.Groups[3],
m.Groups[4].Success ? " ext " + m.Groups[4].Value : ""));
If 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