tags:

views:

460

answers:

2

I'm looking to convert a SQL like statement on the fly to the equivalent regex i.e.

LIKE '%this%' LIKE 'Sm_th' LIKE '[C-P]arsen'

What's the best approach to doing this?

P.S. I'm looking to do this on the .Net Framework (C#).

A: 

I found a Perl module called Regexp::Wildcards. You can try to port it or try Perl.NET. I have a feeling you can write something up yourself too.

eed3si9n
+1  A: 

From your example above, I would attack it like this (I speak in general terms because I do not know C#):

Break it apart by LIKE '...', put the ... pieces into an array. Replace unescaped % signs by .*, underscores by ., and in this case the [C-P]arsen translates directly into regex.

Join the array pieces back together with a pipe, and wrap the result in parentheses, and standard regex bits.

The result would be:

/^(.*this.*|Sm.th|[C-P]arsen)$/

The most important thing here is to be wary of all the ways you can escape data, and which wildcards translate to which regular expressions.

% becomes .*
_ becomes .
Martin