Given a Regex.Replace evaluator with four parameters, is it possible to conditionally add a leading zero to one of the parameters?
NOTE: I am using Visual Studio Ultimate 2013 (with C# version 5).
While the question may be similar to this, a critical difference is that my evaluator has multiple parameters and I need to conditionally add a leading zero to one of the four parameters.
Is there a way to either:
(a) add a conditional component to $3
in the evaluator expression, or
(b) intercept the
Regex.Replace function to apply the conditional leading zero to
parameter $3
?
This is what "conditional" means. *Parameter $3
must hold two numbers. If $3
is between 1 and 9, a leading zero needs to be added; if greater than 9, then no zero needs to be added.
private static void Main(string[] args)
{
const string search = "SCI.9-12.2.2.PO 1.a";
const string pattern = @"SCI\.9-12\.(\d)\.(\d)\.PO (\d{1,2})(.\w)?";
const string evaluator = "SCHS-S$1C$2-$3$4";
/*
* add leading zero to $3 only if $3 is a single-digit
*/
var output = Regex.Replace(search, pattern, evaluator);
Console.WriteLine(output);
}
Here is an example what what I am trying to achieve:
- input: SCI.9-12.2.2.PO 1.a
- output: SCHS-S2C2-01.a
or
- input: SCI.9-12.2.2.PO 10.a
- output: SCHS-S2C2-10.a
In addition to looking for other SO questions and answers, I looked at MSDN but did not see any example that pertained to my situation.