using System; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Linq; public class Test { private static string LookupReplace(string text, List newList) { return "~" + newList.IndexOf(text).ToString() + "~"; } private static string NumberedReplace() { i++; return "~" + i.ToString() + "~"; } public static int i = -1; public static void Main() { string text = "iif(instr(|Wellington, New Zealand|,|,|)>0,|Wellington, New Zealand|,|Wellington, New Zealand| & |, | & |New Zealand|) & | to | & iif(instr(|Jeddah, Saudi Arabia|,|,|)>0,|Jeddah, Saudi Arabia|,|Jeddah, Saudi Arabia| & |, | & |Saudi Arabia|) & iif(|Jeddah, Saudi Arabia|=||,||,| via | & |Jeddah, Saudi Arabia|)"; var re = new Regex(@"\|.*?\|"); var newList = re.Matches(text) .OfType() .Select(m => m.Value) .ToList(); string result = re.Replace(text, x => LookupReplace(x.Value, newList)); Console.WriteLine(result); result = re.Replace(text, x => NumberedReplace()); Console.WriteLine(result); } }