The Regex
class in the System.Text.RegularExpressions
namespace provides the Matches()
method with multiple overloads to find all of the occurrences of a regular expression pattern in a text.
public MatchCollection Matches (string input);
This method takes an input string as input
and performs a search in this string for a pattern.
It returns a MatchCollection
object, which is a collection of all the Match
objects found while matching the regular expression pattern.
If the search returns no matches, an empty collection is returned.
It throws an ArgumentNullException
if the passed input string is null.
In the code below, we have a string variable called textWithCountryNames
that stores the names of different countries.
Now, suppose this is a large body of text and we want to find names of all countries which start with A. The regular expression \b[A]\w+
can be used to find all words in the text which start with A.
The
\b
means to begin searching for matches at the beginning of words, the[A]
means that these matches start with the letter A, and the\w+
means to match one or more word characters.
We create a Regex
object with the desired regular expression and use the Matches()
method to find all occurrences of our desired search pattern.
At last, we iterate through the MatchCollection
object and print all the matched text and its index number.
using System;using System.Text.RegularExpressions;namespace Hello{class RegexTest{static void Main(string[] args){string textWithCountryNames= "Afghanistan,Ecuador,Albania,Italy,Algeria,Gabon,Andorra,Belgium,Angola,Antigua,Jamaica,Argentina,France,Armenia,Australia,Jordan,Austria,Barbados,Belarus";Regex regex = new Regex(@"\b[A]\w+");MatchCollection countryMatch = regex.Matches(textWithCountryNames);foreach(Match match in countryMatch){Console.WriteLine("Country name : {0}, Index : {1}", match.Value, match.Index);}}}};