简体   繁体   中英

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

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

When I'd like to just get

"1"

How can I make C# return me the right thing?

Use Match.Groups[int] indexer.

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; then you must access the match starting at index 1 not index 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.

Specifically, see MSDN

The collection contains one or more System.Text.RegularExpressions.Group objects. If the match is successful, the first element in the collection contains the Group object that corresponds to the entire match. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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