Answer the question
In order to leave comments, you need to log in
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:
Answer the question
In order to leave comments, you need to log in
bool IsMatch(string someString)
{
var patterns = new[]
{
"someExpr1",
"someExpr2",
"someExpr3"
};
return patterns.Any(pattern => Regex.IsMatch(someString, pattern));
}
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;
}
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... */ }
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.
there is a list of files and, depending on the name, you need to parse them differently
IDictionary<string, Action<string>>
and map a regex for an action.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question