如何在C#中使用正则表达式有条件地匹配和替换语句中的单词



我想知道是否有什么可以制作的"开关";在RegEx中替换。

例如,字符串:

圆形正方形未知液体

模式为:w+

假想的替换类似于:

如果(round(则";球";否则如果(平方(,则";方框";else if(液体(那么";水";否则如果(热(,则";火">

结果将是

球盒未知水

这个想法是只使用模式和替换,而不使用任何C#代码。

细节或清晰度:

var Text = "round square unknown liquid";

var Pattern = @"w+";
var Replacement = @"if (round) then Ball else if (square) then Box else if (liquid) then Water else if (hot) then Fire"; // <-- is this somehow possible?
var Result = new Regex(Pattern).Replace(Text, Replacement);
Console.WriteLine(Result);

预期输出:

球盒未知水

这确实是不可能的,也不应该因为不可能而困扰您。

仅仅从纸上造一艘潜艇可能吗?不需要。只需要添加一些配料。

但如果不是因为";仅纯正则表达式";约束,这就是我本该做的:

var dictionaryReplace = new Dictionary<string, string>
{
{"round","Ball"},
{"square","Box"},
{"liquid","Water"},
{"hot","Fire"}, 
};
var Text = "round square unknown liquid";
var Pattern = $"({string.Join("|", dictionaryReplace.Keys)})"; //(round|square|liquid|hot)
var Result = new Regex(Pattern).Replace(Text, x => dictionaryReplace[x.Value]);
Console.WriteLine(Result); //Ball Box unknown Water

最新更新