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?
In regular expressions, the period ( . , also called "dot") is the wildcard pattern which matches any single character. Combined with the asterisk operator . * it will match any number of any characters.
Wildcards are different from the regular expressions used in grep (although they may look similar at times). Wildcards apply to all commands including grep and are used in place of or in combination with operands. Regular Expressions only apply to grep and a few other UNIX commands.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
A wildcard character is used to substitute one or more characters in a string. Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
From http://www.codeproject.com/KB/recipes/wildcardtoregex.aspx:
public static string WildcardToRegex(string pattern) { return "^" + Regex.Escape(pattern) .Replace(@"\*", ".*") .Replace(@"\?", ".") + "$"; }
So something like foo*.xls?
will get transformed to ^foo.*\.xls.$
.
You can do a simple wildcard mach without RegEx using a Visual Basic function called LikeString.
using Microsoft.VisualBasic; using Microsoft.VisualBasic.CompilerServices; if (Operators.LikeString("This is just a test", "*just*", CompareMethod.Text)) { Console.WriteLine("This matched!"); }
If you use CompareMethod.Text
it will compare case-insensitive. For case-sensitive comparison, you can use CompareMethod.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With