C# 具有特定词边界的正则表达式
假设我有一个类型为 (价格+折扣价格)*2-最高价格 以及包含每个元素的替换内容的字典 价格:A1折扣价格:A2最高价格:A3 我怎样才能准确地替换每个短语,而不触及另一个。含义搜索C# 具有特定词边界的正则表达式,c#,regex,word-boundary,C#,Regex,Word Boundary,假设我有一个类型为 (价格+折扣价格)*2-最高价格 以及包含每个元素的替换内容的字典 价格:A1折扣价格:A2最高价格:A3 我怎样才能准确地替换每个短语,而不触及另一个。含义搜索价格不应在折扣价格中修改价格。结果应该是(A1+A2)*2-A3,而不是(A1+折扣_A1)-Max.A1或其他任何内容 谢谢。有关单词边界,您可以使用\b 使用:\b价格\b 但这将取代最高价格中的价格 也许您希望使用常规字符串替换为: “价格+”-->A1++” 例如: string test = "(Price
价格
不应在折扣价格
中修改价格
。结果应该是(A1+A2)*2-A3
,而不是(A1+折扣_A1)-Max.A1
或其他任何内容
谢谢。有关单词边界,您可以使用\b 使用:\b价格\b 但这将取代最高价格中的价格 也许您希望使用常规字符串替换为: “价格+”-->A1++” 例如:
string test = "(Price+Discounted_Price)*2-Max.Price";
string a1 = "7";
string a2 = "3";
string a3 = "4";
test = test.Replace("(Price", "(" + a1);
test = test.Replace("Discounted_Price", a2);
test = test.Replace("Max.Price", a3);
结果:
测试是:(7+3)*2-4如果变量可以由字母数字/下划线/点字符组成,则可以将它们与
[\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);
}
}
请参阅。我不太了解lambda x=>dct.ContainsKey(x.Value)?dct[x.Value]:字典中的x.Value。它还抛出编译错误“无法将lambda转换为类型“int”,因为它不是委托类型”。我们能否以某种方式将其重写为更易于理解的方式,以供以后的代码维护人员使用?谢谢为什么
int
?请提供问题和a中的输入数据;;您的代码也与您的代码相关。正如您在IDEONE上看到的,我的代码可以编译并运行良好。您使用的是静态Regex.Replace
,还是Regex
对象Replace
方法?我在问题中的代码中添加了lambda的解释。我的错误。因为我的同事似乎是这样做的:放置一个解析器来尝试提取每个短语(Price,折扣价格,Max.Price),并循环遍历所有短语,foreach(上面列表中的字符串短语){result=Regex(inStr,短语,dic[phrase])。我认为解析器不起作用;我得查一下他的密码,你是老板。多谢了,Wiktor。
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]);
}