Hello.
Does anyone know if it is possible to increment/decrement values in a Regex Group?
For example, the following code demonstrates capturing two groups called 'value1' and 'value2', and I would like to replace these value with (value1+1) and (value2-1) respectively.
string pattern = @"(?
string result = Regex.Replace(myString, patten, @"${value1}+1/${value2}-1");
I'm basically looking to manipulate multiple numeric values on a multi-line chunk of text.
Any advice would be much appreciated.
Kevin BurtPosted Mar 31, 2008, 5:09 PM
AlanPosted Mar 31, 2008, 12:39 PM
It's possible to do stuff like this using a MatchEvaluator. For example:
using System;
using System.Text.RegularExpressions;
class Program\d{1,2})/(?\d{1,2})";
{
static void Main()
{
string myString = "5/7 and 4/19";
string pattern = @"(?
string result = Regex.Replace(myString, pattern,ReplaceEvaluator);
Console.WriteLine(result);
}
static string ReplaceEvaluator(Match m)
{
int value1 = int.Parse(m.Groups["value1"].Value) + 1;
int value2 = int.Parse(m.Groups["value2"].Value) - 1;
return value1.ToString() + "/" + value2.ToString();
}
}