Dynamic list of regular expressions, find the one that matches.

A

Allan Ebdrup

I have a dynamic list of regular expressions, the expressions don't change
very often but they can change. And I have a single string that I want to
match the regular expressions against and find the first regular expression
that matches the string.
I've gor the regular expressions ordered so that the highest priority is
first (if two or more regular expressions match the string I want the first
one returned)
The code that does this has to perform very well as it is called hundreds of
thousands times a day.
I was thinking of concatenating the regular expressions into one large
expression and have each expression in parenthesis so it captures. Can I
find out what expression matched the string? I know how to do this with a
function in javascript where I would check the arguments array. But how do I
accomplish the same in C# ?

Kind Regards,
Allan Ebdrup
 
N

Nicholas Paldino [.NET/C# MVP]

Allan,

I would keep the dynamic list. It sounds like your list of regular
expressions is pretty long, and I think that the RegEx classes will only be
able to tell you which part of which regular expression matched, not the
whole expression.

Also, I think that concatenating all the expressions together will give
you a performance hit. However, I urge you to test both scenarios yourself,
both for the concatenated string (assuming you can find out which expression
matched) and for the prioritized expression list.

One suggestion, assuming your expressions don't change, I would create a
single instance of the RegEx class for each (or the single) expression, and
make sure you pass the Compiled value in the RegexOptions enumeration to the
constructor. This will cause .NET to compile code instead of interpreting
the regular expression every time. You will definitely get a performance
boost here.

You might also want to explore the ECMAScript enumeration value, since
you implied that you can do this in Javascript, and that is where you are
porting your code from.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top