Reputation: 566
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?
Upvotes: 5
Views: 1718
Reputation: 627607
You may set a flag and set it to true if there was a match and then check if the flag was set to decide whether to throw the exception or return the string:
var str = "89991112233";
var pattern = @"^(?<prefix>8|\+?\d+)\s*(?<code>\d{3})\s*(?<phone>\d{7})\z";
var matched = false;
var result = Regex.Replace(str, pattern, m => {
matched = !matched;
return $"+7 ({m.Groups["code"].Value}) {m.Groups["phone"].Value}";
});
if (!matched)
throw new Exception();
else
return result;
Also, note that to match a whole string with the regex, you need anchors, I added ^
at the start and \z
at the end.
Also, {3,3}
is equal to {3}
and {7,7}
to {7}
.
Upvotes: 5