I’m trying to implement the two oracle wildcards “%” and “_ ” on my c# program using the Regex class. The problem is when I have the wildcard “_” because I need to accept ONLY ONE character but it returns true everytime that I have AT LEAST ONE character. Can you please help me?
Here’s my code:
string filter, string1;
string wildcard1 = "[" + "\\d | " + "\\n | " + "\\s |" + "\\w]+";
string wildcard2 = "[" + "\\d | " + "\\n |" + "\\s | " + "\\w]{1}";
filter = Regex.Replace(filter, "%", wildcard1);
filter = Regex.Replace(filter, "_", wildcard2);
Regex regex1 = new Regex(filter, RegexOptions.IgnoreCase);
MatchCollection a = regex1.Matches(string1);
if (regex1.IsMatch(string1))
{
return true;
}
You have to make these two conversions:
%to.*, which means, “any character, any number of times”_to.which means “any character (one time by default if you don’t specify otherwise)”You also have to add
^at the start and$at the end, to force to match the whole string, and not a part inside it.And finally, and this is very important, you have to escape the original string. If you don’t do it, any special character will be processed by the regex. I.e. a dot
.in original string will be interpreted “as any character” in the regular expression.For example, if you have this SQL LIKE string:
You have to convert it to:
(This will match strings like “Hello, John, is your initial J?”)
First, you have to escape it, so that the
?and any other special character is escaped with backslash\.And then replace
%and_and add the start and end of string characters (^and$).Be also aware that you can create a regex with options, and one of this options let you specify if it’s case sensitive or not. This will also be neccesary to mimic Oracle behaviour.
Finally, use IsMatch(string) method instead of Match.