|
-
Apr 27th, 2011, 01:03 PM
#1
Thread Starter
Hyperactive Member
Compare string to multiple Regex and do different things for all
The question is basically what the title says.
I have a string returned by a function and I want to check if it matches against multiple regexes. Then depending on which regex it matched, I want to do different things.
What is the best way to do this if I want performance and simplicity to add new regexes to match against?
One way I came up with was doing an ordinary If Else If, something like this:
Code:
if(Match(mystring, "regex here"))
{
//Do something
}
else if(Match(mystring, "another regex"))
{
//Do another thing
}
This method works I think but it doesn't have good performance what I have heard and it also is kind of messy I think.
So I thought of the switch, that is much better if you want to compare one object against many others. But I don't really know how to use it with a regex in a good way.
-
Apr 27th, 2011, 01:08 PM
#2
Re: Compare string to multiple Regex and do different things for all
The reason it doesn't have good performance is that you are compiling the regex equations each time. If you had to do this in a loop, you'd create a grouping of regex objects with each of the different conditions and compare against it. Based on which match you got, you'd take an action. (Using enums and switches or using LINQ functions)
If you're only doing this here and there, then perhaps the performance isn't a big deal?
Overall though, regex's still are pretty zippy with short to medium sized data sets. Over large blocks of text, they can be a bit slow though.
Need to re-register ASP.NET?
C:\WINNT\Microsoft.NET\Framework\v#VERSIONNUMBER#\aspnet_regiis -i
(Edit #VERSIONNUMBER# as needed - do a DIR if you don't know)
-
Apr 27th, 2011, 02:10 PM
#3
Thread Starter
Hyperactive Member
Re: Compare string to multiple Regex and do different things for all
Sounds quite overpowered the first thing you mentioned.
I will go with the if else if then. But thank you for your comment anyway (lol it seems I can't give rep to nearly any of you helpers anymore...says I need to give to someone else first...lol I am asking to much at this forum XD)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|