Ответ 1
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();
Почему возникает следующий код:
было найдено 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();
}
}
}
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
возвращает первое совпадение, см. this для того, как получить остальное.
Вместо этого следует использовать Matches
. Затем вы можете использовать:
MatchCollection matches = Regex.Matches(text, search);
Console.WriteLine("there were {0} matches", matches.Count);
Вы должны использовать Regex.Matches
вместо Regex.Match
, если вы хотите вернуть несколько совпадений.