M
M
Michael2016-04-26 12:23:57
Regular Expressions
Michael, 2016-04-26 12:23:57

Is it possible to make a switch case on a regular expression?

Good afternoon!
How to make a construction of the form in c#:

switch(string)
          case регуялрка1:
          case регулярка2:
          case регулярка3:

UPD 1: You need to check that the string matches one of the regular expressions.
UPD 2: there is a list of files and, depending on the name, you need to parse them differently

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Michael, 2016-04-26
@Slider_vm

bool IsMatch(string someString)
{
    var patterns = new[]
    {
        "someExpr1",
        "someExpr2",
        "someExpr3"
    };

    return patterns.Any(pattern => Regex.IsMatch(someString, pattern));
}

More readable than case or if, you can immediately see which patterns match.
Any will not check all patterns, it will exit on the first one it finds and return true
. And to make it the way you want it, here it is:
var someStr = "someValue";
switch (true)
{
    case Regex.IsMatch(someStr, "somePattern1")
        // do...
        break;
    case Regex.IsMatch(someStr, "somePattern2")
        // do...
        break;
    case Regex.IsMatch(someStr, "somePattern3")
        // do...
        break;
}

This will presumably work with C#7, which is not out yet.
For your case, you can try something like this
void Main()
{
    var fileNameList = new List<string> { "fileNameOne", "fileNameTwo" };
    foreach (var fileName in fileNameList)
    {
        var fileAction = FileActions.FirstOrDefault(x => Regex.IsMatch(fileName, x.Key));
        if (fileAction.Key != null)
            fileAction.Value(fileName);
    }
}

IDictionary<string, Action<string>> FileActions = new Dictionary<string, Action<string>>
{
    { "somePatternOne", SomeActionOne },
    { "somePatternTwo", SomeActionTwo }
};

void SomeActionOne(string fileName) { /* Do... */ }
void SomeActionTwo(string fileName) { /* Do... */ }

If the parsing code for each file is significantly different and there is a lot of code, classes can be used instead of methods (polyformism)

D
Dmitry Kovalsky, 2016-04-26
@dmitryKovalskiy

switch case looks for a match for the string variable and its possible value in the case. What do you want to match? That some regular expression is stored in the string variable? Or that string matches one of the regular expressions? If the latter, then your path is if else if.

S
Stanislav Makarov, 2016-04-26
@Nipheris

there is a list of files and, depending on the name, you need to parse them differently

Why not ask this question in the first place? Make IDictionary<string, Action<string>>and map a regex for an action.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question