Comparing two different folders with Regex in C#

Viewed 63

I want to compare if one file is in two different folders.

var reg = new Regex(@"TC__\d{3,4}_8exp$");
var reg1 = new Regex(@"TC_\d{3,4}$");
  
var FileNames_List_Jetzt_Dateien = Directory.GetFiles(@"PATH2", "*.html")
           .Where(path => reg.IsMatch(Path.GetFileNameWithoutExtension(path)))
           .Select(Folder_Jetzt_Dateien =>
               Path.GetFileNameWithoutExtension(Folder_Jetzt_Dateien));

From this one I am getting list :

TC__6493_8exp
TC__6494_8exp
TC__6495_8exp...

From this one:

var TEST_FÄLLE = Directory.GetFiles(@"PATH2", "*.exp")
          .Where(path => reg1.IsMatch(Path.GetFileNameWithoutExtension(path)))
          .Select(Folder_Jetzt_Dateien =>
              Path.GetFileNameWithoutExtension(Folder_Jetzt_Dateien));

I am getting list:

TC_6493
TC_6494
TC_6495...

For me the TC__6493_8exp is the same with TC_6493. How to use Intersect for these two lists with the same elements?

2 Answers

You can write custom comparer and pass it to Intersect method

using System.Collections.Generic;

class FileComparer : IEqualityComparer<string>
{
    const string ext = "_exp8";
    
    public bool Equals(string left, string right)
    {
        if (left.EndsWith(ext) && !right.EndsWith(ext))
        {
            return StripExt(left) == right;
        }
        else if (right.EndsWith(ext))
        {
            return left == StripExt(right);
        }
            
        return left == right;
    }
    
    private static string StripExt(string s)
        => s.Substring(0, s.Length - ext.Length);
    
    public int GetHashCode(string s)
    {
        if (s.EndsWith(ext))
        {
            return StripExt(s).GetHashCode();
        }
        else
        {
            return s.GetHashCode();
        }
    }
}
using System;
using System.Linq;

var files1 = new string[] { "1", "2", "3" };
var files2 = new string[] { "1_ext", "2_exp8", "3_exp8" };

var a = files1.Intersect(files2, new FileComparer());

var res = string.Join(", ", a);
Console.WriteLine(res);

Here is a way to write the custom comparer with a regex:

public static Regex rx = new Regex(@"^(TC_)_?(\d+).*", RegexOptions.Compiled);
public class FilePathComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return rx.Replace(x, "$1$2") == rx.Replace(y, "$1$2");
    }
    public int GetHashCode(string s)
    {
        return rx.Replace(s,"$1$2").GetHashCode();
    }
}

In the code later, just use

var intersected = FileNames_List_Jetzt_Dateien.Intersect(TEST_FÄLLE, new FilePathComparer());

See the C# demo and the regex demo.

The ^(TC_)_?(\d+).* regex matches

  • ^ - start of string
  • (TC_) - Group 1 ($1): TC_
  • _? - an optional underscore
  • (\d+) - Group 2 ($2): one or more digits
  • .* - the rest of the string.
Related