I have a string and multiple regex's, for example a regex that checks if the string is a number only, if it starts with character X and so on. I have different codes running depending on what regex gets matched, like this:
if (Regex.IsMatch(myString, regex1))
{
//number
}
else if (Regex.IsMatch(myString, regex2))
{
//something else
}
else if (Regex.IsMatch(myString, regex3))
{
//something else
}
and so on. However, this looks very clunky as I have like 10 regex's to go through, so can I do the same thing using switch/case? If so, can I be provided with an example?
I am using .NET 2.0 and WinForms.
You could make a more complex regex like /(a)|(b)|(c)/ and then check match.Groups afterwards, which pattern matched:
You can keep a dictionary of associations - match function and handling logic, then just loop through matches and once it return true - execute associated handling logic so you'll end up with pretty simple
foreach
loop:This cannot be done as you describe because switch can only be used with: bool, char string, int, enum or a corresponding nullable type.
It boils down to how much code you have for each Regex case.
If it's only a line or two of code
I say stick with the if-else. Not only is it more direct and to the point, but it's also easier to read.
If it's complex, or you use the switch several times
If what you have is rather complicated, you might want to look into implementing the Strategy Pattern or something like that.
Bottom Line
There are times where switch statements are fine, but when you find yourself using the same switch multiple times, or there is a good amount of code for each case, the strategy pattern can really help out, especially when it comes to maintainability.
The only way to do this is with a switch-true statement (not recommended).
EDIT: Buh Buh mentioned the fact that the case expressions must be constant, so the code won't compile.
There is another very roundabout way to solve this. Remember, I am pointing this out not as a recommendation, but as an example of why an if block is better.
If your regexes are in an array
regexes
, you can do this:One 'non-clunky' solution is to use a simplified version of the Chain Of Responsibility design pattern. In fact, this pattern was made to handle situations exactly like David has described here.
Code
In your case, you simply need to map strings to activities. You can define a base class that iterates through the chain and performs the defined activity when a match is found, or forwards the input on to the next option.
Then create derived classes for as many options as you need. Each defines:
Something like:
Usage
Output
Another advantage to using this pattern is that if you need to add additional options later, you just need to define additional derived classes and hook them into the chain. The calling code doesn't need to change at all!