364,033 Members | 4753 Browsing Online
Community for Developers & IT Professionals
Bytes IT Community

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

Craig Kenisston
P: n/a
Craig Kenisston

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



Nov 16 '05 #1
Share this Question
Share on Google+
1 Reply


Chris R. Timmons
P: n/a
Chris R. Timmons
"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/
Nov 16 '05 #2

Post your reply

Help answer this question



Didn't find the answer to your C# / C Sharp question?

You can also browse similar questions: C# / C Sharp