使用正則表達式
static bool TryParse(string pattern, string text, out string[] wildcardValues)
{
//^and $ means that whole string must be matched
// Regex.Escape (http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape(v=vs.110).aspx)
// (.+) means capture at least one character and place it in match.Groups
var regexPattern = string.Format("^{0}$", Regex.Escape(pattern).Replace(@"\*", "(.+)"));
var match = Regex.Match(text, regexPattern, RegexOptions.Singleline);
if (!match.Success)
{
wildcardValues = null;
return false;
}
//skip the first one since it is the whole text
wildcardValues = match.Groups.Cast<Group>().Skip(1).Select(i => i.Value).ToArray();
return true;
}
使用範例
string[] wildcardValues;
if(TryParse("Hello *. * * to *", "Hello World. Happy holidays to all", out wildcardValues))
{
//it's a match
//wildcardValues contains the values of the wildcard which is
//['World','Happy','holidays','all'] in this sample
}
順便說一句,你並不真正需要的正則表達式這一點,這是矯枉過正。通過使用string.Split將模式分割成令牌來實現自己的算法,然後使用string.IndexOf找到每個令牌。雖然使用正則表達式確實導致代碼更短
這可能有所幫助:http://stackoverflow.com/a/15275806/607162 – Johnny5