My task is to verify a string with regex, than perform replacement if it match succeed or throw Exception if string don't match.
Obviously, I could check Regex.IsMatch
and then call Regex.Replace
or throw Exception:
var str = "89991112233";
var pattern = @"(?<prefix>8|\+?\d+)\s*(?<code>\d{3,3})\s*(?<phone>\d{7,7})";
var replace = "+7 ${code} ${phone}";
if (!Regex.IsMatch(str, pattern))
throw new Exception();
else
return Regex.Replace(str, pattern, replace);
but it requires two identical matching operations.
Can I perform regex check and get both if string was matching and the replacement in single call in .Net?