Reputation: 863
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.
Upvotes: 4
Views: 5116
Reputation: 141542
Here is a general approach, with which you can fiddle here.
Note the change to your regex. It uses \.
instead of .
inside a literal @
string; that will match a period instead of the wildcard character class.
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");
// the following will not match
files.Add("AB_FBER_20161011948111txt");
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
Upvotes: 5
Reputation: 3668
This code works for me
var files = new List<string>
{
"AB_DBER_2016101194814.txt",
"AB_EBER_2016101194815.txt",
"AB_FBER_2016101194811.txt"
};
var refFiles = new List<string>
{
"AB_DBER_[0-9]{13,13}.txt",
"AB_EBER_[0-9]{13,13}.txt",
"AB_FBER_[0-9]{13,13}.txt"
};
foreach (var patternFile in refFiles)
{
var regularExp = new Regex(patternFile);
foreach (var file in files)
{
if (regularExp.IsMatch(file))
{
Console.WriteLine(file);
}
}
}
Upvotes: 1