blue blue -4 years ago 98
C# Question

Find if an item exists in a list using regex pattern

I've a list of files with timestamp appended to it.I Also have another list which contains regex patterns. I wanted to verify all patterns in 'refFiles' exists in 'files' for not.

Below is the samples files,

List<string> files = new List<string>();
files.Add("AB_DBER_2016101194814.txt");
files.Add("AB_EBER_2016101194815.txt");
files.Add("AB_FBER_2016101194811.txt");


This is the reference patterns:

List<string> refFiles = new List<string>();
refFiles.Add("AB_DBER_[0-9]{13,13}.txt");
refFiles.Add("AB_EBER_[0-9]{13,13}.txt");
refFiles.Add("AB_FBER_[0-9]{13,13}.txt");


I wanted to do something like:

foreach (var file in refFiles )
{
//if file has a match in files then I need to do some code
}


I wanted to know how I can find the regex pattern in second list to verify that matching patern exists in first list.

Answer Source

Here is a general approach, with which you can fiddle here https://dotnetfiddle.net/HDP4vL

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

public class Program
{
    public static void Main()
    {
        List<string> files = new List<string>();
        files.Add("AB_DBER_2016101194814.txt");
        files.Add("AB_EBER_2016101194815.txt");
        files.Add("AB_FBER_2016101194811.txt");
        files.Add("This_Does_Not_Match.txt");

        List<string> refFiles = new List<string>();
        refFiles.Add("AB_DBER_[0-9]{13,13}.txt");
        refFiles.Add("AB_EBER_[0-9]{13,13}.txt");
        refFiles.Add("AB_FBER_[0-9]{13,13}.txt");

        foreach (var pattern in refFiles)
        {
            var regex = new Regex(pattern);

            foreach (var file in files)
            {
                if (regex.IsMatch(file))
                {
                    Console.WriteLine(file);
                }
            }
        }
    }
}

You can also use LINQ:

foreach (var file in files)
{
    if (refFiles.Any(pattern => Regex.IsMatch(file, pattern)))
    {
        Console.WriteLine(file);
    }
}

In both cases, this is the output:

AB_DBER_2016101194814.txt
AB_EBER_2016101194815.txt
AB_FBER_2016101194811.txt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download