How to find all matching words for a pattern using Regex in C#
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.
Syntax
public MatchCollection Matches (string input);
-
This method takes an input string as
inputand performs a search in this string for a pattern. -
It returns a
MatchCollectionobject, which is a collection of all theMatchobjects found while matching the regular expression pattern. -
If the search returns no matches, an empty collection is returned.
-
It throws an
ArgumentNullExceptionif 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
\bmeans 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.
Code
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);}}}};