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

发布于 2025-01-17 23:42:10 字数 744 浏览 0 评论 0原文

我想知道是否有将“开关”替换为REGEX中的“开关”。

例如,字符串:

圆形正方形未知液体

和图案是:\ w+

虚构替换类似:

if(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);

预期输出:

球盒未知水

I wonder if there's anyway to make "switch" replaces in RegEx.

For example, string:

round square unknown liquid

And pattern is: \w+

And imaginary replacement something like:

if (round) then "Ball" else if (square) then "Box" else if (liquid)
then "Water" else if (hot) then "Fire"

And result would be

Ball Box unknown Water

The idea is to use only patterns and replacements, without any C# code.

Details or clarity:

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);

Expected output:

Ball Box unknown Water

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奈何桥上唱咆哮 2025-01-24 23:42:10

这确实是不可能的,不可能打扰您。

是否可以通过纸制造潜艇?否。只需要添加一些成分即可。

但是,如果不是“只有纯正的正则”约束,这就是我要做的:

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

This is indeed not possible and it should not bother you that it is not possible.

Is it possible to build a submarine just from paper? No. Just need to add a few ingredients.

But were it not for the "only pure regex" constraint, this is what I would have done:

var dictionaryReplace = new Dictionary<string, string>
{
    {"round","Ball"},
    {"square","Box"},
    {"liquid","Water"},
    {"hot","Fire"}, 
};

var Text = "round square unknown liquid";

var Pattern = 
quot;({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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文