|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Regex.Replace to format a phone number...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. Mike Edgewood wrote:
> One of our most frequently encountered errors in number entry is an Remove the question mark at the end. A lazy .* does nothing when it's > 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)") 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 "Mike Edgewood" <itm***@gmail.com> wrote in message In general you want to use the ^ and $ anchors to make sure you match news:1148671221.151202.226080@j33g2000cwa.googlegroups.com... > Absolutely perfect! > > And thanks for the detailed explanation. > everything from the beginning to the end of the string. |
|||||||||||||||||||||||