【问题标题】:C# substring html contentC# 子字符串 html 内容
【发布时间】:2011-06-16 14:41:09
【问题描述】:

我使用 tinymce 存储数据,每个表之前都有占位符

输入数据时的编辑器视图:

#data1
[html table1] 

#data2
[html table2]

#data3
[html table3]

这存储在用<p>标签包裹的数据库中。

我想根据传递的参数剥离并获取 html 表。

string getTable(string placeholder)
{
     string content = db.getData();

     //placeholder = data1, return html table 1 substring data from content variable
     return [html table1]; //html string

    //placeholder = data2
     return [html table2]; //html string
}

如何使用 C# 实现这一点?

【问题讨论】:

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


    【解决方案1】:

    我认为this regex might be reliable #data2([^#]+|#(?!data))+</table> (click to see the example),但这取决于您的输入,它可能会中断。 You can't trust regex to parse html.

    #data1
    <table id="t1">
    <tr><td>#</td></tr>
    </table>
    
    #data2
    <table id="t2">
    <tr><td>#</td></tr>
    </table>
    
    #data3
    <table id="t3">
    <tr><td>#</td></tr>
    </table>
    

    要通过您could try &lt;table.*?id=.t1.&gt;([^&lt;]|\&lt;(?!/table))+&lt;/table&gt; 的ID 匹配表。

    【讨论】:

    • 你的回答给了我另一个想法,我可以使用 ids 而不是占位符,让我为此编辑你的正则表达式并测试它。
    • 知道为什么这个正则表达式无法匹配 id \s* 上的表吗?.*
    【解决方案2】:

    在这种情况下,您可以尝试使用正则表达式。虽然它不能完全证明(HTML 不是常规语言),但如果您没有嵌套表,它应该可以正常工作。

    string strRegex = @"(?<=#data1)\s*?<table.*?>.*</table>";
    Regex myRegex = new Regex(strRegex, RegexOptions.Singleline);
    string strTargetString = @"#data1 <table><tr><td> asdsad</td></tr></table>";
    
    foreach (Match myMatch in myRegex.Matches(strTargetString))
    {
      if (myMatch.Success)
      {
         // myMatch.Value contains table
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 2011-01-16
      • 2019-11-16
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多