Sign in to follow this  
Headkaze

[.net] Wildcard searching

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this