【问题标题】:My Regex.Replace doesn't work我的 Regex.Replace 不起作用
【发布时间】:2013-01-11 18:06:49
【问题描述】:

嘿,我目前正在尝试替换字符串中的 html。即<strong>text</strong> 必须是<b>text</b> 等等(我意识到b 标签被认为是过时的)

我知道我不应该使用正则表达式来解决这个问题,但这是我目前唯一的选择

我的代码:

//replace strong
text = Regex.Replace(text, "<strong>.*?</strong>", "<b>$1</b>");

//replace em
text = Regex.Replace(text, "<em>.*?</em>", "<i>$1</i>");

这里的问题是正则表达式替换了标签并且将文本设置为$1。如何避免这种情况? (顺便说一句,我在 C# 中。)

【问题讨论】:

    标签: c# html regex string


    【解决方案1】:

    $1 将使用匹配中第一个 capture 的值。但是你没有在比赛中指定任何捕获组,所以$1没有什么可以替代的。

    使用(…) 在正则表达式中捕获:

    text = Regex.Replace(text, "<strong>(.*?)</strong>", "<b>$1</b>");
    

    【讨论】:

      【解决方案2】:

      请注意,以下答案只是一种解决方法;最好写一个合适的正则表达式。

      var text = "<strong>asfdweqwe121</strong><em>test</em>";
      
      text = text.Replace("<strong>", "<b>");
      text = text.Replace("</strong>", "</b>");
      text = text.Replace("<em>", "<i>");
      text = text.Replace("</em>", "</i>");
      

      【讨论】:

        【解决方案3】:

        您也可以考虑使用:

        text = Regex.Replace(text, "<strong>(.*?)</strong>", "<b>$1</b>", RegexOptions.Singleline);
        

        请注意,RegexOptions.Singleline 是允许. 匹配换行符(LF、\x0A)所必需的,而. 模式默认无法匹配。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-02-04
          • 1970-01-01
          • 2013-04-21
          • 2012-07-23
          • 2012-03-13
          • 2015-11-03
          • 1970-01-01
          相关资源
          最近更新 更多