Friday, February 4, 2011

What code would I use to convert a SQL like expression to a regex on the fly?

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#).

  • 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.

    From eed3si9n
  • 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 .
    
    From Martin

0 comments:

Post a Comment