从html字符串中获取ID值

时间:2017-12-07 19:42:34

标签: c#

我抓住了outlook的约会描述并得到了这个字符串:

<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
  ID: 123456<br>
  Comments: blah blah
</body>
</html>

我需要使用c#代码获取ID值123456和注释值。我只能使用标准的.NET库,也就是说,我不能使用html敏捷包。我做了这样的事情:

var index = html.IndexOf("ID");
var IDindex = index + "ID".Length + 2 ;
var IDvalue = html.Substring( IDIndex,6);

但我喜欢做一些更强大的东西来处理例如ID长度变化。

1 个答案:

答案 0 :(得分:1)

我会尝试使用regular expression match并检查第一个捕获的正则表达式组ID:\s*(\d+)<br />

using System;
using System.Text.RegularExpressions;

namespace RegexExample
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (Match match in Regex.Matches("ID: 12345<br />", @"ID:\s*(\d+)<br />"))
                Console.WriteLine(match.Groups[1]);
        }
    }
}