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 can do a simple wildcard mach without RegEx using a Visual Basic function called LikeString.
If you use
CompareMethod.Text
it will compare case-insensitive. For case-sensitive comparison, you can useCompareMethod.Binary
.More info here: http://www.henrikbrinch.dk/Blog/2012/02/14/Wildcard-matching-in-C
MSDN: http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compilerservices.operators.likestring%28v=vs.100%29.ASPX
Windows and *nux treat wildcards differently.
*
,?
and.
are processed in a very complex way by Windows, one's presence or position would change another's meaning. While *nux keeps it simple, all it does is just one simple pattern match. Besides that, Windows matches?
for 0 or 1 chars, Linux matches it for exactly 1 chars.I didn't find authoritative documents on this matter, here is just my conclusion based on days of tests on Windows 8/XP (command line,
dir
command to be specific, and theDirectory.GetFiles
method uses the same rules too) and Ubuntu Server 12.04.1 (ls
command). I made tens of common and uncommon cases work, although there'are many failed cases too.The current answer by Gabe, works like *nux. If you also want a Windows style one, and are willing to accept the imperfection, then here it is:
There's a funny thing, even the Windows API PathMatchSpec does not agree with FindFirstFile. Just try
a1*.
,FindFirstFile
says it matchesa1
,PathMatchSpec
says not.I think @Dmitri has nice solution at Matching strings with wildcard https://stackoverflow.com/a/30300521/1726296
Based on his solution, I have created two extension methods. (credit goes to him)
May be helpful.
Usage:
or
The correct regular expression formulation of the glob expression
d*
is^d
, which means match anything that starts withd
.(The
@
quoting is not necessary in this case, but good practice since many regexes use backslash escapes that need to be left alone, and it also indicates to the reader that this string is special).You need to convert your wildcard expression to a regular expression. For example:
d*
means that it should match zero or more "d
" characters. So any string is a valid match. Tryd+
instead!In order to have support for wildcard patterns I would replace the wildcards with the RegEx equivalents. Like
*
becomes.*
and?
becomes.?
. Then your expression above becomesd.*