【问题标题】:Substring from the beginning of a word单词开头的子字符串
【发布时间】:2018-05-25 02:38:49
【问题描述】:

请求的 HTTP GET 响应如下所示

    <html>
      <head>        <script type="text/javascript">----</script>        <script type="text/javascript">---</script>             <title>Detailed Notes</title>
      </head>
      <body style="background-color: #FFFFFF; border-width: 0px; font-family: sans-serif; font-size: 13; color: #000000">           <p>this is one note&nbsp;</p>  </body>      </html>

我将其作为字符串获取,我必须从中读取正文部分。

我尝试了 HtmlAgility 包,但由于 html 内容中的一些特殊情况,HTML 解析失败(我认为注释脚本中的某些内容会导致此问题)。

所以要读取标签内容,我正在考虑 SubString 操作。

Like SubString 从&lt;body tag 开始。

我们如何从文本中的一个单词的开头做 SubString?

【问题讨论】:

  • 那么,您是否要编辑您的问题以包含一个问题?请阅读How to Ask
  • 您只需要 Body 的内容吗?或者我们也应该包括“”吗?你想过正则表达式吗?
  • 只是正文内容。是的,我想 Regx 很有用。但是我猜body标签的CSS样式可能会引起一些麻烦

标签: c# substring


【解决方案1】:

使用简单的SubString()IndexOf() + LastIndexOf():

string BodyContent = input.Substring(0, input.LastIndexOf("</body>") - 1).Substring(input.IndexOf("<body"));
BodyContent = BodyContent.Substring(BodyContent.IndexOf(">") + 1).Trim();

这将返回:
&lt;p&gt; this is one note&amp;nbsp;&lt;/p&gt;

string FullBody = input.Substring(0, input.LastIndexOf("</body>") + 7).Substring(input.IndexOf("<body")).Trim();

这将返回:

&lt;body style = background-color: #FFFFFF; border-width: 0px; font-family: sans-serif; font-size: 13; color: #000000' &gt;&lt; p &gt; this is one note&amp;nbsp;&lt;/p&gt; &lt;/body&gt;

【讨论】:

    【解决方案2】:

    " 将导致问题,因此您需要在获得请求源后替换每个 "

    WebClient client = new WebClient(); // make an instance of webclient
    string source = client.DownloadString("url").Replace("\"",",,"); // get the html source and escape " with any charachter
    string code = "<body style=\"background-color: #FFFFFF; border-width: 0px; font-family: sans-serif; font-size: 13; color: #000000\">           <p>this is one note&nbsp;</p>  </body>";
    MatchCollection m0 = Regex.Matches(code, "(<body)(?<body>.*?)(</body>)", RegexOptions.Singleline); // use RE to get between tags
    foreach (Match m in m0) // loop through the results
    {
        string result = m.Groups["body"].Value.Replace(",,", "\""); // get the result and replace the " back
    }
    

    【讨论】:

    • BODY标签的内联css因响应而异
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 2010-10-24
    • 2016-01-13
    • 2018-12-22
    相关资源
    最近更新 更多