string st = Convert.ToString(Regex.Match(str, "id=\"user_online\">\\d*").Groups[0]); 

How to get the value of \ d * from here?

    2 answers 2

     const int wholePhraseGroupIndex = 0; const int numberGroupIndex = 1; // Комилируем регулярное выражение для ускорения поиска Regex regex = new Regex("id=\"user_online\">(\\d+)", RegexOptions.Compiled); // Сравниваем строку с паттерном Match match = regex.Match(str); // Проверяем, что строка совпала if (!match.Success) throw new FormatException("Строка имеет неверный формат: " + str); // Извлекаем содержимое скобок string numberStr = match.Groups[numberGroupIndex].Value; // Парсим значение int number = int.Parse(numberStr, CultureInfo.InvariantCulture); 
    • Where should the variable be written? - deced
    • @deced In st : D Groups[0] - the entire matched result of Groups[1] - the contents of the first bracket, etc. - Lunar Whisper
    • And why do you need Convert.ToString ? - Wiktor Stribiżew
    • @ WiktorStribiżew is absolutely unnecessary, did not change, so that the code remained similar to the author’s and he understood what the changes were. - Lunar Whisper
    • So describe the changes and remove too much. It will be clearer and more valuable. - Wiktor Stribiżew

    A reliable way to get part of a match is named groups:

     var str = "id=\"user_online\">33"; var match = Regex.Match(str, "id=\"user_online\">(?'usersCount'\\d*)"); if (match.Success) { var usersCount = match.Groups["usersCount"].Value; // "33" } 

    An alternative is the use of the mechanism of positive lookbehind. In your case, search for those \d* , which are preceded by a tag:

     var match = Regex.Match(str, "(?<=id=\"user_online\">)\\d*"); if (match.Success) { var usersCount = match.Value; // 33 } 

    Well, or you can wrap \d* in brackets and get Groups[1] , but this approach may break when rewriting the regular schedule in the future.

    Don't forget that parsing HTML with regular expressions is a bad idea. There are much simpler ways to extract tag values .

    • how many years I live in the world, but did not know that there are named groups in the regulars. : D - Lunar Whisper