Match string against list of RegEx rules using switch...case statement

1k Views Asked by At

I've a code snippet written in JScript.Net for FiddlerScript and trying to re-write the same in C# to use as Fiddler extension. I'm not familiar with C# syntax, so need help.

Here's the existing code snippet in JScript.NET, which I'm trying to convert into C#:

var sHostname = oSession.hostname;

switch(sHostname) {
    case /example1.com/i.test(sHostname) && sHostname:
    case /example2.com/i.test(sHostname) && sHostname:
    case /example3.com/i.test(sHostname) && sHostname:
        MessageBox.Show("Matched: " + sHostname);
    default:
        FiddlerApplication.Log.LogString("No match for hostname.");
}

Here's something I tried in C#, but this is very primitive:

var sHostname = oSession.hostname;
string[] patterns = { @"[a-z]", @"[0-9]", @"example[0-9]", @"[a-z0-9.]", @"\w+" }; // a collection of about 20K+ pattern entries, yes 20K+, and stored in separate class
IList<string> patternList = new ReadOnlyCollection<string>(patterns);

var status = false;
var pattern = "";
foreach (string p in patternList)
{
    if (Regex.IsMatch(sHostname, p, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace))
    {
        pattern = p;
        status = true;
        break;
    }
}

if (status)
{
    System.Diagnostics.Debug.WriteLine("Matched: " + pattern);
    // Other code
} else
{
    System.Diagnostics.Debug.WriteLine("No match found");
    // Other code
}

As a newbie to C#, I came across many stuff:

  • Regex compiled version is better than creating new object every time. I'm not sure specifying switches RegexOptions::Compiled | RegexOptions::IgnoreCase will be same as creating the list once and using over iterations. Any hint on this will be helpful.
  • Usage of LINQ instead of boilerplate code.
  • And many more good things in C# world

All I'm interested is a match or not (boolean true / false value), like Any() and not performing any match, split, etc. Again, this code need to be executed over several hundred times per second in Fiddler, so it need to be efficient enough to match against over 20K+ patterns list for a specified input string. I know it sounds bit crazy, so need help from experts.

FYI, I'm using Visual Studio 2013, so not sure if I can use C# 7 syntax. I'd be very much interested if better things can be done in C# 7 or higher VS versions.

Thank you in advance!

0

There are 0 best solutions below