I need to perform Wildcard (*
, ?
, etc.) search on a string.
This is what I have done:
string input = "Message";
string pattern = "d*";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
if (regex.IsMatch(input))
{
MessageBox.Show("Found");
}
else
{
MessageBox.Show("Not Found");
}
With the above code "Found" block is hitting but actually it should not!
If my pattern is "e*" then only "Found" should hit.
My understanding or requirement is d* search should find the text containing "d" followed by any characters.
Should I change my pattern as "d.*" and "e.*"? Is there any support in .NET for Wild Card which internally does it while using Regex class?
You must escape special Regex symbols in input wildcard pattern (for example pattern
*.txt
will equivalent to^.*\.txt$
) So slashes, braces and many special symbols must be replaced with@"\" + s
, wheres
- special Regex symbol.All upper code is not correct to the end.
This is because when searching zz*foo* or zz* you will not get correct results.
And if you search "abcd*" in "abcd" in TotalCommander will he find a abcd file so all upper code is wrong.
Here is the correct code.
You may want to use
WildcardPattern
fromSystem.Management.Automation
assembly. See my answer here.From http://www.codeproject.com/KB/recipes/wildcardtoregex.aspx:
So something like
foo*.xls?
will get transformed to^foo.*\.xls.$
.