【问题标题】:How to rewrite a string by pattern如何按模式重写字符串
【发布时间】:2012-07-12 01:50:32
【问题描述】:

我有一个字符串,其中“特殊区域”用大括号括起来:

{intIncG}/{intIncD}/02-{yy}

我需要遍历 {} 之间的所有这些元素并根据它们的内容替换它们。在 C# 中最好的代码结构是什么?

我不能只做一个替换,因为我需要知道每个“特殊区域{}”的索引才能用正确的值替换它。

【问题讨论】:

  • 只是索引?您没有根据 {} 中的内容更改替换?
  • 两者都需要考虑 - 索引和内容 - 实际代码。

标签: c# string iterator string-formatting


【解决方案1】:
Regex rgx = new Regex( @"\({[^\}]*\})");
string output = rgx.Replace(input, new MatchEvaluator(DoStuff));


static string DoStuff(Match match)
{
//Here you have access to match.Index, and match.Value so can do something different for Match1, Match2, etc.
//You can easily strip the {'s off the value by 

   string value = match.Value.Substring(1, match.Value.Length-2);

//Then call a function which takes value and index to get the string to pass back to be susbstituted

}

【讨论】:

  • 是的,但是input.Replace(match.Groups[i].Value, GetValueForIndex(i)); 行不会失败,以防我将有一个{intInc_G}/{intInc_G}/{yy} 形式的字符串。它将替换两个出现的子字符串,而我需要替换唯一的一个 - 当前处理的索引处的那个。
  • 比我写的“手工”方法要优雅得多。谢谢!
【解决方案2】:

string.Replace 就可以了。

var updatedString = myString.Replace("{intIncG}", "something");

对每个不同的字符串执行一次。


更新:

由于您需要{ 的索引来生成替换字符串(就像您commented 一样),您可以使用Regex.Matches查找{ 的索引 - 每个Matches 集合中的Match 对象将在字符串中包含索引。

【讨论】:

  • 我的错,我不能这样做,因为我需要知道一个特殊区域的索引才能形成正确的“东西”。我应该在一个问题中提到它。现在我添加了这个要求。对不起。
【解决方案3】:

使用Regex.Replace:

用指定的替换字符串替换所有出现的由正则表达式定义的字符模式。

来自msdn

【讨论】:

    【解决方案4】:

    您可以定义一个函数并加入它的输出——因此您只需要遍历部分而不是每个替换规则。

    private IEnumerable<string> Traverse(string input)
    {
      int index = 0;
      string[] parts = input.Split(new[] {'/'});
      foreach(var part in parts)
      {
        index++;
        string retVal = string.Empty;
        switch(part)
        {
          case "{intIncG}":
            retVal = "a"; // or something based on index!
            break;
          case "{intIncD}":
            retVal = "b"; // or something based on index!
            break;
    
          ...
        }
        yield return retVal;
      }
    }
    
    string replaced = string.Join("/", Traverse(inputString));
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2022-07-12
      • 2021-04-24
      • 2018-09-08
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2015-01-30
      相关资源
      最近更新 更多