Regex.Replace to format a phone number...

M

Mike Edgewood

One of our most frequently encountered errors in number entry is an
extra digit at the end that doesn't belong. Looking for a
Regex.Replace to go in my DataGridView.CellFormatting.

Regex.Replace(inputStr, _
".*?(\d{3}).*?(\d{3}).*?(\d{4}).*?", "($1) $2-$3)")

The behavior regex.replace is not what I expect.

input: 123-456-78901
returns: (123) 456-78901

The extra digit does not match any pattern within a capture group, so
why is it showing up as part of capture group 3?

input: 1234567890a
returns: (123) 456-7890a

The 3rd capture groups seems to be returning everything rather than
just 4 numeric characters. Running regex.Match returns 3 groups with
correct results, but regex.replace is not producing the same expected
result and is confusing the hell out of me.

I want to keep this as simple and quick as possible because, according
to the documentation, CellFormatting is called on every paint request.
 
M

Markus Stoeger

Mike said:
One of our most frequently encountered errors in number entry is an
extra digit at the end that doesn't belong. Looking for a
Regex.Replace to go in my DataGridView.CellFormatting.

Regex.Replace(inputStr, _
".*?(\d{3}).*?(\d{3}).*?(\d{4}).*?", "($1) $2-$3)")

Remove the question mark at the end. A lazy .* does nothing when it's
placed at the end, as the whole rest of the pattern is already matched,
no matter what follows.

So in your pattern the last digit actually isn't included in the 3rd
group, but it doesn't get replaced either, as it isn't even matched by
the pattern. It just stays where it is.

Making the .* at the end greedy by removing the ? makes the pattern
match (and replace) the whole thing.

hth,
Max
 
B

Ben Voigt

Mike Edgewood said:
Absolutely perfect!

And thanks for the detailed explanation.
In general you want to use the ^ and $ anchors to make sure you match
everything from the beginning to the end of the string.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top