如果您的变量可以由字母数字/下划线/点字符组成,您可以将它们与[\w.]+ 正则表达式模式匹配,并添加包含. 的边界:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
var s = "(Price+Discounted_Price)*2-Max.Price";
var dct = new Dictionary<string, string>();
dct.Add("Price", "A1");
dct.Add("Discounted_Price", "A2");
dct.Add("Max.Price","A3");
var res = Regex.Replace(s, @"(?<![\w.])[\w.]+(?![\w.])", // Find all matches with the regex inside s
x => dct.ContainsKey(x.Value) ? // Does the dictionary contain the key that equals the matched text?
dct[x.Value] : // Use the value for the key if it is present to replace current match
x.Value); // Otherwise, insert the match found back into the result
Console.WriteLine(res);
}
}
见IDEONE demo
如果匹配前面有一个单词或点字符,(?<![\w.]) 否定前瞻将导致匹配失败,如果后面有一个单词或点字符,(?![\w.]) 否定前瞻将导致匹配失败。
请注意,[\w.]+ 允许在前导和尾随位置使用点,因此,您可能希望将其替换为 \w+(?:\.\w+)* 并用作 @"(?<![\w.])\w+(?:\.\w+)*(?![\w.])"。
更新
由于您已经将要替换的关键字提取为列表,因此您需要使用更复杂的单词边界,不包括点:
var listAbove = new List<string> { "Price", "Discounted_Price", "Max.Price" };
var result = s;
foreach (string phrase in listAbove)
{
result = Regex.Replace(result, @"\b(?<![\w.])" + Regex.Escape(phrase) + @"\b(?![\w.])", dct[phrase]);
}
见IDEONE demo。