【问题标题】:Split paragraph from html string and remove empty paragraph从 html 字符串中拆分段落并删除空段落
【发布时间】:2013-03-19 13:07:06
【问题描述】:

我有一串html。我想将所有段落拆分为一个数组列表。但拆分后的段落不应为空。分割后的段落应该包含一些普通文本,如果它只包含html文本并且里面没有普通文本如:<htmltag>     </htmltag>,那么它应该被销毁或不分割。

这是一个如何在 html 字符串中分割段落的示例:

System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(htmlString, @"<p>\s*(.+?)\s*</p>");
ArrayList groupCollection = new ArrayList();
while (m.Success)
{
   groupCollection.Add(m.Value);
   m = m.NextMatch();
}
ArrayList paragraphs = new ArrayList();
if (groupCollection.Count > 0)
{
   foreach (object item in groupCollection)
   {
      paragraphs.Add(item);
   }
}

上面的代码可以拆分所有段落,但它不能像我上面所说的那样识别哪个段落是空的。

【问题讨论】:

  • 你试过什么?
  • 我已经尝试使用正则表达式从 html 字符串中拆分出所有段落。但是我不确定它是空的。
  • 你能发布你的代码有问题吗..?
  • 如果我使用RegularExpressions,那么它只会帮助我分割段落,但如果有一些文字如:&lt;htmltag&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/htmltag&gt;,那么我不知道如何删除这些空html标签。跨度>
  • [stackoverflow.com/questions/3708734/… 这可能会对您有所帮助。它与您的问题有些相同...

标签: c# html regex


【解决方案1】:

我有自己的问题的答案。这是我自己版本的代码:

System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(htmlString, @"<p>\s*(.+?)\s*</p>");
    ArrayList groupCollection = new ArrayList();
    while (m.Success)
    {
        groupCollection.Add(m.Value);
        m = m.NextMatch();
    }
    ArrayList paragraphs = new ArrayList();
    if (groupCollection.Count > 0)
    {
        foreach (object item in groupCollection)
        {
            try
            {
                System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("<[^>]*>");
                // replace all matches with empty string
                string str = rx.Replace(item.ToString(), "");
                string str1 = str.Replace("&nbsp;", "");
                if (!String.IsNullOrEmpty(str1))
                {
                    paragraphs.Add(item.ToString());
                }
            }
            catch
            {
                //This try-catch just prevent future error.
            }
        }
    }

在上面的代码中。你可以看到我先删除了段落中的所有 html 标签,然后替换了 html 字符串中的所有空。这将帮助我识别一个空段落。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 2014-12-25
    • 1970-01-01
    • 2015-12-16
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多