"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/