如何在 C# 中使用正则表达式有条件匹配和替换语句中的单词
我想知道是否有将“开关”替换为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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这确实是不可能的,不可能打扰您。
是否可以通过纸制造潜艇?否。只需要添加一些成分即可。
但是,如果不是“只有纯正的正则”约束,这就是我要做的:
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: