[.net] Wildcard searching

Started by
3 comments, last by Headkaze 14 years, 10 months ago
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".
Advertisement
Sounds like you're looking for regular expressions.
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
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 "*".
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);
----------------------------------------MagosX.com
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;}

This topic is closed to new replies.

Advertisement