Search This Blog

Tuesday 17 February 2015

Match a string against a List of Regex Patterns in C# - Better way

when you have list of Regex Patterns and you want to check whether your string matches any one of the patterns, then doing it using Lamda Expressions is an efficient way.

Code:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Program
{
public static void Main()
{

List<Regex> lstpat= new List<Regex>();
lstpat.Add(new Regex(@"\d{2}"));
lstpat.Add(new Regex(@"\d{4}"));
string str = "qqw1q1q2q1q2q2q3qqwqw";

if(lstpat.Exists(x=>x.Match(str).Success == true))
System.Console.Write("exists");
else
System.Console.Write("no");
}

}

Output
no

if i give str = "qq11";

output will be exists.

if you are not doing it using Lamda Expressions you may need to write one loop for finding Matches.
                    foreach (Regex pattern in lstSmartTagPatterns)
                    {
                        lstMatches.Add(pattern.Match(str));
                    }
then i need find a Match found or not in another loop.
                    foreach (Match result in lstMatches)
                    {
                        if(result.Success)
                                   System.Console.Write("exists");
                         else
                                   System.Console.Write("Doesnt exist");
                    }

found doing first way is better. open for improvements.. share urs...