【问题标题】:remove first occurring paragraph tag contents in string删除字符串中第一个出现的段落标签内容
【发布时间】:2014-06-18 11:37:43
【问题描述】:

如何删除字符串中第一个出现的段落标签内容。

Actual String
<p>Hello</p> <p>World</p>

Result
<p>World</p>

一种选择是找到第一个&lt;p&gt;和第一个&lt;/p&gt;的位置,然后用“”替换所有内容以定位&lt;/p&gt;

如何使用正则表达式来实现?

【问题讨论】:

    标签: c# asp.net regex vb.net


    【解决方案1】:

    使用Regex.Replace 方法将计数(可能发生替换的次数)定义为1

    Regex rgx     = new Regex(@"<p>.*?</p>*");
    String input  = @"<p>Hello</p> <p>World</p>";
    String result = rgx.Replace(input, "", 1);
    

    【讨论】:

      【解决方案2】:

      除了关于使用正则表达式解析 html 的警告...

      A.如果第一段总是从字符串的开头开始

      • 搜索:^&lt;p&gt;.*?&lt;/p&gt;
      • 替换:空字符串
      • ^ 锚断言我们位于字符串的开头。
      • 懒惰的.*?确保我们只匹配到第一个关闭&lt;/p&gt;

      在 C# 中:

      string resultString = Regex.Replace(yourstring, "^<p>.*?</p>", "");
      

      B.如果第一段可以从任何地方开始

      • 搜索:(?s)(\A.*?)&lt;p&gt;.*?&lt;/p&gt;
      • 替换:在委托函数中,返回组1。
      • (?s) 允许点匹配换行符,以防您的第一段出现在第一行之后
      • (\A.*?) 中,\A 断言我们在字符串的开头,然后惰性.*? 匹配第一段之前的所有内容。这都被捕获到第 1 组。
      • &lt;p&gt;.*?&lt;/p&gt; 匹配段落
      • 替换的是第 1 组,因此该段落被删除。

      这是一个完整的 C# 程序来展示它是如何工作的(请参阅online demo 底部的输出)。

      using System;
      using System.Text.RegularExpressions;
      class Program
      {
      static void Main() {
      var myRegex = new Regex(@"(?s)(\A.*?)<p>.*?</p>");
      string s1 = @"Hey! <p>Hello</p> <p>World</p>";
      
      string replaced = myRegex.Replace(s1, delegate(Match m) {
      return m.Groups[1].Value;
      });
      Console.WriteLine(replaced);
      
      } // END Main
      } // END Program
      

      【讨论】:

      • 仅供参考添加了两种方法的完整解释。 :)
      【解决方案3】:

      您可以像这样在字符串中捕获组:

      string input = @"<p>Hello</p> <p>World</p>";
      string pattern = @"<p>(\w*)</p>";
      MatchCollection matches = Regex.Matches(input, pattern);
      // matches[0] contains <p>Hello</p>
      // matches[1] contains <p>World</p>
      

      【讨论】:

        猜你喜欢
        • 2014-01-07
        • 1970-01-01
        • 2018-05-16
        • 2014-12-25
        • 2015-07-07
        • 2013-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多