By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,680 Members | 2,173 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,680 IT Pros & Developers. It's quick & easy.

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

P: n/a

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


P: n/a
"Craig Kenisston" <Cr************@hotmail.com> wrote in
news:e3**************@TK2MSFTNGP10.phx.gbl:

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 !


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

This discussion thread is closed

Replies have been disabled for this discussion.