Why is Regex.Replace giving me weird result for last group

Viewed 68

A simple example:

Regex.Replace("12345678910999999999", @"(\d{3})(\d{3})(\d{3})(\d{2})", "$1-$2-$3 $4")

This outputs to:

123-456-789 10999999999

But why? I have specifically set the group index i need. And that group index contains the exact value (checked in debugger).

Here is a fiddle: https://dotnetfiddle.net/dkAPx3

2 Answers

Match the rest of the string with .* to truncate it:

Regex.Replace("12345678910999999999", @"^(\d{3})(\d{3})(\d{3})(\d{2}).*", "$1-$2-$3 $4")

I'd also add ^ at the start to match the beginning of the string.

See the .NET regex demo.

Your regex has matched and replaced only "first" part of string, add .* to the end of the pattern:

Regex.Replace("12345678910999999999", @"(\d{3})(\d{3})(\d{3})(\d{2}).*", "$1-$2-$3 $4"); // results in "123-456-789 10"
Related