0
"<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?

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.