为什么我的正则表达式不起作用?

时间:2015-10-12 10:05:50

标签: c# html regex parsing console-application

我有这个程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;

namespace Reviews_browser_test
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine(enter good, that u want to find: ");
            string tovar = Console.ReadLine();
            string page = "http://www.ulmart.ru/search?string=&rootCategory=&sort=6";
            page = page.Insert(35, tovar); // inserts good's id into url


            HttpWebRequest site = (HttpWebRequest)WebRequest.Create(page);

            HttpWebResponse response = (HttpWebResponse)site.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader read = new StreamReader(dataStream);
            String data = read.ReadToEnd();
            Console.WriteLine(data);

            System.IO.File.WriteAllText("ulmart.html", data);

            Console.ReadKey();


            Match m;


            string pattern = "<span[^>]*?>[0-9]{4,10}</span>";


            m = Regex.Match(data, pattern);
            while (m.Success)
            {
                Console.WriteLine("Found an id " + m.Groups[1] + " at string "+ m.Groups[1].Index);
                m = m.NextMatch();
            }

            Console.ReadKey();
        }
    }
}

我想从html文件中获取所有id号码。但我不知道,为什么使用这个正则表达式它找不到任何东西,而notepad ++发现每个id都很好。 应该找到的html字符串示例,使用此正则表达式:

<span class="num">3609304</span>

我的错误在哪里?

1 个答案:

答案 0 :(得分:1)

解决问题的最佳方法是使用HtmlAgilityPack。将其安装为NuGet包,并使用以下方法:

public List<string> HtmlAgilityPackGetNumericSpan4to10(string html)
{
        var vals = new List<string>();
        HtmlAgilityPack.HtmlDocument hap;
        Uri uriResult;
        if (Uri.TryCreate(html, UriKind.Absolute, out uriResult) 
                            && uriResult.Scheme == Uri.UriSchemeHttp)
        { // html is a URL 
            var doc = new HtmlAgilityPack.HtmlWeb();
            hap = doc.Load(uriResult.AbsoluteUri);
        }
        else
        { // html is a string
            hap = new HtmlAgilityPack.HtmlDocument();
            hap.LoadHtml(html);
        }
        var nodes = hap.DocumentNode.SelectNodes("//span[@class='num']");
        if (nodes != null)
        {
            foreach (var node in nodes)
            {
                var val = node.InnerText;
                if (val.ToCharArray().All(p => Char.IsDigit(p)) 
                                 && val.Length >= 4 && val.Length <= 10)
                    vals.Add(val);
            }
        }
        return vals;
}

使用"//span[@class='num']",我们只会收集span属性值等于class的{​​{1}}代码。使用num,我们检查内部文本是否全部为数字,其长度是4到10。

只有您的示例字符串的结果:

enter image description here