[英]Replace Multiple References of a pattern with Regex
我有一个以下形式的字符串
$KL\U#, $AS\gehaeuse#, $KL\tol_plus#, $KL\tol_minus#
基本上,该字符串由以下部分组成
我现在想用一些有意义的文本替换每个部分。 因此,我需要提取这些部分,根据每个部分中的文本进行操作,然后将结果替换为该部分。 因此,结果字符串应如下所示:
12V, 0603, +20%, -20%
该部分中未包含的逗号和其他所有内容将保持原样,这些部分将被有意义的值替换。
问题:您能否以正则表达式模式帮助我,找出这些部分的位置,以便我可以替换它们?
您需要使用Regex.Replace
方法并使用MatchEvaluator
委托来确定替换值。
您需要的模式可以是$
然后是#
,然后是#
。 我们将中间的位放在方括号中,以便将其作为单独的组存储在结果中。
\$([^#]+)#
完整的事情可能是这样的(由您来完成正确的适当替换逻辑):
string value = @"$KL\U#, $AS\gehaeuse#, $KL\tol_plus#, $KL\tol_minus#";
string result = Regex.Replace(value, @"\$([^#]+)#", m =>
{
// This method takes the matching value and needs to return the correct replacement
// m.Value is e.g. "$KL\U#", m.Groups[1].Value is the bit in ()s between $ and #
switch (m.Groups[1].Value)
{
case @"KL\U":
return "12V";
case @"AS\gehaeuse":
return "0603";
case @"KL\tol_plus":
return "+20%";
case @"KL\tol_minus":
return "-20%";
default:
return m.Groups[1].Value;
}
});
就匹配模式而言,您需要:
\$[^#]+#
您的其余问题不是很清楚。 如果您需要使用一些有意义的值替换原始字符串,只需循环进行匹配即可:
var str = @"$KL\U#, $AS\gehaeuse#, $KL\tol_plus#, $KL\tol_minus#";
foreach (Match match in Regex.Matches(str, @"\$[^#]+#"))
{
str = str.Replace(match.ToString(), "something meaningful");
}
除此之外,您还必须提供更多背景信息
您确定不想仅执行纯字符串操作吗?
var str = @"$KL\U#, $AS\gehaeuse#, $KL\tol_plus#, $KL\tol_minus#";
string ReturnManipulatedString(string str)
{
var list = str.split("$");
string newValues = string.Empty;
foreach (string st in str)
{
var temp = st.split("#");
newValues += ManipulateStuff(temp[0]);
if (0 < temp.Count();
newValues += temp[1];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.