簡體   English   中英

如何在 C# 中使用正則表達式有條件地匹配和替換語句中的單詞

[英]How to conditionally match and replace words in a statement using regex in C#

我想知道是否有辦法在 RegEx 中進行“切換”替換。

例如,字符串:

圓形方形未知液體

模式是: \w+

假想的替代品是這樣的:

如果(圓形)則“球” 否則如果(方形)則“盒子” 否則如果(液體)則“水” 否則如果(熱)則“火”

結果是

球盒未知水

這個想法是只使用模式和替換,沒有任何 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);

預計 output:

球盒未知水

這確實是不可能的,你不應該因為這是不可能的而煩惱。

有可能只用紙建造一艘潛艇嗎? 不需要。只需要添加一些成分。

但如果不是因為“唯一的純正則表達式”約束,這就是我會做的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM