1
var find1 = Regex.Match(s,"<td class=.additional-attribute.>(.*?)<", RegexOptions.Singleline | RegexOptions.IgnoreCase).Groups[1].Value;

Этому выражения соответствует 5 результатов. Мне нужно вывести первые 2.

Это не помогает :(

var find1 = Regex.Match(s,"<td class=.additional-attribute.>(.*?)<", RegexOptions.Singleline | RegexOptions.IgnoreCase).Groups[2].Value;

(Groups[1] поменял на Groups[2])

6
  • 1) парсить html регулярками неправильно 2) Вы входные данные забыли указать
    – tym32167
    4 мая 2019 в 22:36
  • 3) var firstTwo = Regex.Matches(s,"<td class=.additional-attribute.>(.*?)<", RegexOptions.Singleline | RegexOptions.IgnoreCase).OfType<Match>().Take(2).ToArray(); ?
    – tym32167
    4 мая 2019 в 22:39
  • Я только учусь. Все делаю неправильно, знаю :) Ошибка 'System.Text.RegularExpressions.MatchCollection' does not contain a definition for 'OfType' and no extension method 'OfType' accepting a first argument of type 'System.Text.RegularExpressions.MatchCollection' could be found (are you missing a using directive or an assembly reference?) Есть альтернатива? Требуется без доп. библиотек. Все это в "урезанной" среде. Без компилятора.
    – Kevus
    4 мая 2019 в 22:42
  • Regex.Matches(s,"<td class=.additional-attribute.>(.*?)<", RegexOptions.Singleline | RegexOptions.IgnoreCase)[0].Value
    – tym32167
    4 мая 2019 в 23:14
  • Match - один результат. Matches - все результаты. Или можно использовать NextMatch. 5 мая 2019 в 10:01

1 ответ 1

1

Чтобы получить первые два совпадения (тут значения первой захватываемой подмаски), найдите сначала их все с помощью Regex.Matches, а потом воспользуйтесь LINQ:

var results = Regex.Matches(s, "(?si)<td class=.additional-attribute.>(.*?)<")
        .Cast<Match>()
        .Take(2)                          // Взять первые два
        .Select(x => x.Groups[1].Value)
        .ToList();

Пример кода:

var s = "<td class='additional-attribute'>1</td><td class='additional-attribute'>2</td><td class='additional-attribute'>3</td>";
var result = Regex.Matches(s, "(?si)<td class=.additional-attribute.>(.*?)<")
            .Cast<Match>()
            .Take(2)
            .Select(x => x.Groups[1].Value)
            .ToList();
foreach (var n in result)
    Console.WriteLine(n);

Результат: 1 и 2.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.