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);
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"
}
另一种方法是使用积极的后视机制。在您的情况下,搜索\d*前面有标签的那些:
var match = Regex.Match(str, "(?<=id=\"user_online\">)\\d*");
if (match.Success)
{
var usersCount = match.Value; // 33
}
获得部分匹配的可靠方法是命名组:
另一种方法是使用积极的后视机制。在您的情况下,搜索
\d*前面有标签的那些:好吧,或者你可以将它包裹
\d*在括号中并获取Groups[1]它,但是这种方法可能会在将来重写正则表达式时失效。不要忘记用正则表达式解析 HTML 是个坏主意。从标签中提取值有很多更简单的方法。