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

C

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
 
C

Chris R. Timmons

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);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top