.NET regex match and replace

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();
    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}.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top