Regex and MatchCollection

Using Regex, we can replace string with regular expression. Here is the sample of using Regex.

using System.Text.RegularExpressions;


string mail = "test";
MatchCollection mcMail = Regex.Matches(mail, @"\w+?@\w+?\.(comnetin)");
string phoneNo = "My Phone Number is 98393 94893";
MatchCollection mcPhoneNo = Regex.Matches(phoneNo, @"\d\d\d\d\d \d\d\d\d\d");
if(mcMail.Count>0)
mail = mcMail[0].ToString();
if(mcPhoneNo.Count>0)
phoneNo = mcPhoneNo[0].ToString();


If we have a string with multiple phone number like "My Phone Number is 98393 94893 other no is 93759 84595", we can use Multiple MatchCollection as follows,


string phoneNo = "My Phone Number is 98393 94893 other no is 93759 84595";
MatchCollection mcPhoneNo = Regex.Matches(phoneNo, @"\d\d\d\d\d \d\d\d\d\d");


if (mcPhoneNo.Count > 0)
{
phoneNo = "";
for (int i = 0; i < phoneno ="phoneNo+mcPhoneNo[i].ToString()+">

From the MatchCollection, there are some properties available. Here is explonation for some of that properties.

Success:
Indicates whether a match was found. You should test this value before processing the match.

Index
Indicates the position in the string where the match starts.

Length
Indicates the length of the substring that matches the pattern. Value Equals the substring that did match the pattern.

Groups
Returns a collection of Group objects.

...S.VinothkumaR.

No comments: