用Regex替换模式的多个引用

时间:2014-11-19 13:58:14

标签: c# regex

我有一个字符串,其格式如下

$KL\U#, $AS\gehaeuse#, $KL\tol_plus#, $KL\tol_minus#

这个字符串基本上由以下部分组成

  • $ =分隔符开始
  • (有些文字)
  • #= Delimiter End
  • (所有这n次)

我现在想用一些有意义的文字替换这些部分。因此,我需要提取这些部分,根据每个部分中的文本执行某些操作,然后用结果替换该部分。因此,结果字符串应如下所示:

12V, 0603, +20%, -20%

逗号和该部分中未包含的所有其他内容保持不变,这些部分将被有意义的值替换。

对于这个问题:你能帮我找到一个正则表达式模式,找出这些部分的位置,以便我可以替换它们吗?

3 个答案:

答案 0 :(得分:2)

您需要使用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;
    }
});

答案 1 :(得分:1)

就匹配模式而言,您需要:

\$[^#]+#

你的其余问题不是很清楚。如果您需要用一些有意义的值替换原始字符串,只需循环匹配:

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

除此之外,你必须提供更多的背景

答案 2 :(得分:0)

你确定你不想做简单的字符串操作吗?

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];
    }
}