• Advertisement
Sign in to follow this  

[.net] Wildcard searching

This topic is 3151 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I need to write a search system that can use the "*" wilcard character in a string. For example consider these strings
string1 = "My Game [Date: 2003]"
string2 = "[Date: *]"
string3 = ""
string4 = "*"
I need to be able to say
if string1 contains string2 then string3 = string4
So in other words
if "My Game [Date: 2003]" contains "[Date: *]" then string3 = "*"
Meaning that string3 should now equal "2003".

Share this post


Link to post
Share on other sites
Advertisement
Yes I know about regular expressions. I have the following method I use:

public static bool IsWildcardMatch(string originalString, string searchString)
{
if (!searchString.Contains("*"))
return false;

Regex regEx = new Regex("^" + Regex.Escape(searchString).Replace("\\*", ".*").Replace("\\?", ".") + "$");

return regEx.IsMatch(originalString);
}


I need a similar method that will match part of a string (Eg. like String.Contains()) allowing only one "*" and have an "out string wildcardString" parameter that will output what was inside the "*".

Share this post


Link to post
Share on other sites
Check if there's a match, and if it is get the value using a group:

var s = "My Game [Date: 2003]";
var p = "\\[Date: (?<Year>.*?)\\]";
var m = System.Text.RegularExpressions.Regex.Match(s, p);
if(m.Success) MessageBox(m.Groups["Year"].Value);

Share this post


Link to post
Share on other sites
Thanks Magos that's exactly what I was looking for. Here is the resulting method if anyone else is interested.

public static bool IsWildcardMatch(string originalString, string searchString, out string[] wildcardArray, bool ignoreCase)
{
wildcardArray = null;

Regex regEx = new Regex("^" + Regex.Escape(searchString).Replace("\\*", "(?<Asterisk>.*?)").Replace("\\?", "(?<QuestionMark>.?)") + "$", (ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None));
Match regMatch = regEx.Match(originalString);

if (regMatch.Success)
{
List<string> wildcardList = new List<string>();

foreach (Capture capture in regMatch.Groups["Asterisk"].Captures)
wildcardList.Add(capture.Value);

wildcardArray = wildcardList.ToArray();
}

return regMatch.Success;
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement