【问题标题】:String replace even and odd values in C# [duplicate]字符串替换C#中的偶数和奇数值[重复]
【发布时间】:2016-12-16 13:16:57
【问题描述】:

我在 C# 中有一个带有“wiki 语法”的字符串,我想替换其中的值。

"My '''random''' text with '''bold''' words."

translate to:

"My <b>random</b> text with <b>bold</b> words."

问题是我想将成对的值替换为不同的值。

odd ''' => <b>
even ''' => </b>

【问题讨论】:

  • 到目前为止你尝试过什么?
  • 用空格+'''和'''+空格会更好吗?
  • @LeonidMalyshev 在一般情况下你不能依赖它。
  • 怎么样:Regex.Replace(input, "'''(.*?)'''", "&lt;b&gt;$1&lt;/b&gt;")

标签: c# regex replace


【解决方案1】:

再添加一个选项:Regex.Replace 可以与指定替换字符串的回调一起使用:

var txt = "My '''random''' text with '''bold''' words.";

int i = 0;
var newtext = new Regex("'''").Replace(txt, m => i++ % 2 == 0 ? "<B>" : "</B>" );

【讨论】:

【解决方案2】:

Evil hack:包括空格和

replace " '''" with <b>
and "''' " with </b>

工作直到由于某种原因失败;)

【讨论】:

    【解决方案3】:

    这应该也可以:

    static string ReplaceEvenOdd(string s, string syntax, string odd, string even)
    {
        string[] split = s.Split(new[] { syntax }, StringSplitOptions.None);
        string result = string.Empty;
        for (int i = 0; i < split.Length; i++)
        {
            result += split[i];
            if (i < split.Length - 1)
                result += (i + 1) % 2 == 0 ? even : odd;
        }
        return result;
    }
    

    【讨论】:

    • 我相信它不会起作用,因为 - 尽管 OP 中没有说明 - ''' 将在上下文中匹配。至少在 SO cmets 中是这样完成的。让 OP 提供反馈。
    【解决方案4】:

    你可以这样做。

    string c = "My '''random''' text with '''bold''' words.";
    
    string[] tags = {"<b>", "</b>"};
    
    for (int i = 0, index; (index = c.IndexOf("'''", StringComparison.Ordinal)) > 0; i++)
    {
        var temp = c.Remove(index, 3);
        c = temp.Insert(index, tags[i % 2]);
    }
    
    • 获取'''的索引
    • 如果找不到匹配,IndexOf 将返回负数,否则将给出''' 的位置
    • 从该位置删除 3 个字符(即''')。
    • 如果计数器甚至插入&lt;b&gt; 否则&lt;/b&gt;

    【讨论】:

      【解决方案5】:

      虽然这有一个类似于其他答案的循环,但一个细微的区别是开始和结束标签的选择——而不是计算模 2 来确定我们是使用开始标签还是结束标签,我在大小为 2 的数组:

      String[] replaceText = new String[] { "<B>", "</B>" };
      

      根据变量iReplacerIndex选择元素

      replaceText[iReplacerIndex]  // Gives either the opening or closing tag 
      

      并通过减去 1 在所需值之间切换。

      iReplacerIndex = 1 - iReplacerIndex; // If last used was an opening tag, 
                                           // then next required is a closing tag 
      

      上面的内容也可以很容易地检查不匹配的标签——如果iReplacerIndex在循环之后不为0,那么就有一个不匹配的标签。

      整个代码如下(为了清楚起见,它比需要的更长):

      String sourceText = "My '''random''' text with '''bold''' words.";
      int sourceLength = sourceText.Length;
      String searchText = "'''";
      int searchLength = searchText.Length;
      String[] replaceText = new String[] { "<B>", "</B>" };
      
      int iReplacerIndex = 0
        , iStartIndex = 0 
        , iStopIndex = sourceText.Length - 1;
      System.Text.StringBuilder sbCache = new System.Text.StringBuilder(sourceText.Length * 2);
      
      do
      {
          iStopIndex = sourceText.IndexOf(searchText, iStartIndex);
      
          if (iStopIndex == -1)
          {
              sbCache.Append(sourceText.Substring(iStartIndex, sourceLength - iStartIndex));
          }
          else
          { 
          sbCache.Append(sourceText.Substring(iStartIndex, iStopIndex - iStartIndex));
          sbCache.Append(replaceText[iReplacerIndex]);
      
          iReplacerIndex = 1 - iReplacerIndex;
          iStartIndex = iStopIndex + searchLength;
          }
      } while (iStopIndex != -1);
      
      Console.WriteLine(sbCache.ToString());
      

      【讨论】:

        猜你喜欢
        • 2019-06-07
        • 2022-12-12
        • 1970-01-01
        • 2021-03-13
        • 2021-03-29
        • 1970-01-01
        • 2022-01-17
        • 2022-08-14
        • 2019-01-14
        相关资源
        最近更新 更多