Connecting Tech Pros Worldwide Help | Site Map

Using Regex to create a SQL's "like" like function.

Craig Kenisston
Guest
 
Posts: n/a
#1: Nov 16 '05

Hi,

I need to write a function that should behave like the SQL's "like" operator
on a list of words.
I was wondering if I can use Regex directly to do this job. But I've been
reading about regex and it supports very different characters and behaves
different.

So, I'm looking for an advise. I'd like to know if it is feasable or not, I
mean, if dotnet Regex implementation could handle it.
Or, if anyone can quote a link for a sample or a code snippet to start with,
it'd be great !

Thanks in advance,


CK



Chris R. Timmons
Guest
 
Posts: n/a
#2: Nov 16 '05

re: Using Regex to create a SQL's "like" like function.


"Craig Kenisston" <CraigKenisston@hotmail.com> wrote in
news:e3JLEDGmEHA.1452@TK2MSFTNGP10.phx.gbl:
[color=blue]
>
> Hi,
>
> I need to write a function that should behave like the SQL's
> "like" operator on a list of words.
> I was wondering if I can use Regex directly to do this job. But
> I've been reading about regex and it supports very different
> characters and behaves different.
>
> So, I'm looking for an advise. I'd like to know if it is
> feasable or not, I mean, if dotnet Regex implementation could
> handle it. Or, if anyone can quote a link for a sample or a code
> snippet to start with, it'd be great ![/color]

Craig,

See if this works:

/* Ex:
*
* bool isMatch =
* IsSqlLikeMatch("abcdef", "[az]_%[^qz]ef");
*
* should return true.
*/

private bool IsSqlLikeMatch(string input, string pattern)
{
/* Turn "off" all regular expression related syntax in
* the pattern string. */
pattern = Regex.Escape(pattern);

/* Replace the SQL LIKE wildcard metacharacters with the
* equivalent regular expression metacharacters. */
pattern = pattern.Replace("%", ".*?").Replace("_", ".");

/* The previous call to Regex.Escape actually turned off
* too many metacharacters, i.e. those which are recognized by
* both the regular expression engine and the SQL LIKE
* statement ([...] and [^...]). Those metacharacters have
* to be manually unescaped here. */
pattern = pattern.Replace(@"\[", "[").Replace(@"\]",
"]").Replace(@"\^", "^");

return Regex.IsMatch(input, pattern);
}


--
Hope this helps.

Chris.
-------------
C.R. Timmons Consulting, Inc.
http://www.crtimmonsinc.com/
Closed Thread