Как найти несколько вхождений с группами регулярных выражений?
Почему следующий код приводит к:
было 1 совпадений для 'the'
и не:
было 3 матча за 'the'
using System;
using System.Text.RegularExpressions;
namespace TestRegex82723223
{
class Program
{
static void Main(string[] args)
{
string text = "C# is the best language there is in the world.";
string search = "the";
Match match = Regex.Match(text, search);
Console.WriteLine("there was {0} matches for '{1}'", match.Groups.Count, match.Value);
Console.ReadLine();
}
}
}
4 ответа
Решение
string text = "C# is the best language there is in the world.";
string search = "the";
MatchCollection matches = Regex.Matches(text, search);
Console.WriteLine("there was {0} matches for '{1}'", matches.Count, search);
Console.ReadLine();
Выполняет поиск в указанной входной строке первого вхождения указанного регулярного выражения.
Вместо этого используйте Regex.Matches(String, String).
Выполняет поиск в указанной входной строке всех вхождений указанного регулярного выражения.
Match
возвращает первое совпадение, посмотрите, как получить остальное.
Вы должны использовать Matches
вместо. Тогда вы можете использовать:
MatchCollection matches = Regex.Matches(text, search);
Console.WriteLine("there were {0} matches", matches.Count);
Вы должны использовать Regex.Matches
вместо Regex.Match
если вы хотите вернуть несколько совпадений.