简体   繁体   English

C# 正则表达式问题

[英]C# regex problem

"<div class=\"standings-rank\">([0-9]{1,2})</div>"

Here's my regex.这是我的正则表达式。 I want to Match it but C# returns me something like我想匹配它,但 C# 给我返回类似

"<div class=\"standings-rank\">1</div>"

When I'd like to just get当我想得到

"1"

How can I make C# return me the right thing?我怎样才能让 C# 归还给我正确的东西?

Use Match.Groups[int] indexer.使用Match.Groups[int]索引器。

Regex regex = new Regex("<div class=\"standings-rank\">([0-9]{1,2})</div>");
string str = "<div class=\"standings-rank\">1</div>";
string value = regex.Match(str).Groups[1].Value;

Console.WriteLine(value); // Writes "1"

Assuming you have a Regex declared as follows:假设您有一个声明如下的正则表达式:

 Regex pattern = new Regex("<div class=\"standings-rank\">([0-9]{1,2})</div>");

and are testing said regex via the Match method;并正在通过Match方法测试所述正则表达式; then you must access the match starting at index 1 not index 0;那么您必须从索引 1 而不是索引 0 开始访问匹配项;

 pattern.Match("<div class=\"standings-rank\">1</div>").Groups[1].Value

This will return the expected value;这将返回预期值; index 0 will return the whole matched string. index 0 将返回整个匹配的字符串。

Specifically, see MSDN具体见MSDN

The collection contains one or more System.Text.RegularExpressions.Group objects.该集合包含一个或多个 System.Text.RegularExpressions.Group 对象。 If the match is successful, the first element in the collection contains the Group object that corresponds to the entire match.如果匹配成功,则集合中的第一个元素包含对应于整个匹配的 Group object。 Each subsequent element represents a captured group, if the regular expression includes capturing groups.如果正则表达式包括捕获组,则每个后续元素都表示一个捕获组。 If the match is unsuccessful, the collection contains a single System.Text.RegularExpressions.Group object whose Success property is false and whose Value property equals String.Empty.如果匹配不成功,则集合包含单个 System.Text.RegularExpressions.Group object,其 Success 属性为 false 且 Value 属性等于 String.Empty。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM