Just add this to the end, it will be your 11th group (and it won’t get the extension if it really doesn’t have 2 digits or more
(\d{2,})
The code will be:
Regex.Replace(phone,
@"^\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d{2,})$",
"+1 $1$2$3-$4$5$6-$7$8$9$10 Ext $11");
If this is not necessary, do the following:
(\d{2,})?
- , , ,
, Ext, MatchEvaluator
- ( , )
Regex.Replace(phone,
@"^\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d{2,})$",
"+1 $1$2$3-$4$5$6-$7$8$9$10 Ext $11");
match =>
{
var returnVal = "+1 ";
for(int i = 1; i <= 3; i++)
{
returnVal += match.Groups[i].Value;
if(i == 3 || i == 6)
returnVal += "-";
}
returnVal += match.Groups[11].Success ? " Ext " + match.Groups[11] : "" )
return returnVal;
}
)