Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#提取字符串的某些部分_C#_Asp.net_Regex - Fatal编程技术网

C#提取字符串的某些部分

C#提取字符串的某些部分,c#,asp.net,regex,C#,Asp.net,Regex,我有一个控制台应用程序,它通过WebRequest方法(http)解析HTML文档。问题实际上是从返回的html代码中提取数据 下面是我感兴趣的html片段: <span class="header">Number of People:</span> <span class="peopleCount">1001</span> <!-- this is the line we are interested in! --> <spa

我有一个控制台应用程序,它通过WebRequest方法(http)解析HTML文档。问题实际上是从返回的html代码中提取数据

下面是我感兴趣的html片段:

<span class="header">Number of People:</span>
<span class="peopleCount">1001</span>  <!-- this is the line we are interested in! -->
<span class="footer">As of June 2009.</span>
人数:
1001
截至2009年6月。
假设上面的html包含在一个名为“responseHtml”的字符串中。我只想提取“人员计数”值(第二行)

我搜索了流上的堆栈,找到了一些可以工作的代码:

但是,当我实现它时,它不起作用-我认为它不喜欢我将HTML标记放入正则表达式的方式:

        string responseHtml; // this is already filled with html code above ^^
        string insideBrackets = null;


        Regex regex = new Regex("\\<span class=\"peopleCount\">?<TextInsideBrackets>\\w+\\</span>");

        Match match = regex.Match(responseHtml);
        if (match.Success)
        {
            insideBrackets = match.Groups["TextInsideBrackets"].Value;
            Console.WriteLine(insideBrackets);
        }
字符串响应html;//上面已经填充了html代码^^
字符串insideBrackets=null;
正则表达式正则表达式=新正则表达式(“\\?\\w+\\”;
Match=regex.Match(responseHtml);
如果(匹配成功)
{
insideBrackets=match.Groups[“TextInsideBrackets”].Value;
控制台。写入线(内部回退);
}
上面提到的都不起作用,这和html的方括号有关吗?我想要的只是特定跨度标记之间的文本值

提前谢谢

不正确

你需要:

(?<TextInsideBrackets>...)
(?…)

我假设您要执行命名捕获

你应该使用


正则表达式正则表达式=新正则表达式(“\\(?\\w+\”);

而不是


正则表达式正则表达式=新正则表达式(“\\?\\w+\\”;

试试这个:

Regex regex = new Regex("class=\\\"peopleCount\\\"\\>(?<data>[^\\<]*)",
RegexOptions.CultureInvariant
| RegexOptions.Compiled
);

Regex Regex=new Regex(“class=\\\\”peopleCount\\\\”\\>(?[^\\)并在第一次结束感谢您的帮助,我发现我缺少了圆括号!很高兴它成功了!只需一个注释,您可以(也应该)如果您想多次重复使用regex实例,即使是跨多个线程。regex是线程安全的,并且由于RegexOptions.Compiled参数,这个特定的实例得到了特殊处理。干杯