string[] ss = { "345.00", "456", "2345.90", "341.56" };
foreach (string s in ss)
{
Console.WriteLine(Regex.Replace(s, @"^(\d*)\d(?:\.\d+)?$",
@"$$${1}9.00"));
}
output:
$349.00
$459.00
$2349.00
$349.00
Initially, (\d*)
matches as many digits as it can and stores them in capturing group #1 (for example, it matches 341
in 341.56
). Then it backs off one position to let \d
match the final digit (group #1 now contains just 34
). Finally, (?:\.\d+)?
matches the fraction if there is one (.56
in this case).
In the substitution, $$
inserts a dollar sign ($
has a special meaning in substitutions, so you have to escape it with another $
). ${1}
inserts the contents of capturing group #1 (34
in the case of 341.56
). Normally you can use just $1
, but this time the group reference is followed by another digit in the substitution, so it would look like I was referring to group #19. The braces around the 1
tell it unambiguously I want group #1 followed by 9
. Finally, .00
completes the substitution.
That regex you came up uses named capture groups, so you use ${price1}
instead of ${1}
to insert the first part of the number. The other two capturing groups aren't needed. In fact, there's a lot of stuff in there that doesn't really belong. And I see you're removing the fractional part now instead of replacing it with .00
.
One more thing: you don't need to call IsMatch()
before starting a replacement; that's taken care of by the Replace()
method.