想象一个赌博游戏,您必须匹配所有三个单词才能获得奖励。
因此,如果您获得HHH
,则会获得奖励。
我希望能够用W
来模仿任何字母。
例如:
HWW = HHH
和
HHW = HHH
但是
WWW = WWW
我该怎么做?
答案 0 :(得分:3)
在将字符串匹配到模式之前,将通配符字符更改为与任何字符都匹配的字符。像这样:
// this method change W wild-card character to a character that match anything
private static bool MatchToString(string stringToMatch, string pattern) {
Regex r = new Regex(pattern.Replace("W", "."));
return r.Match(stringToMatch).Success;
}
static void Main() {
// these are matches
Console.WriteLine(MatchToString("HHH", "HWW"));
Console.WriteLine(MatchToString("HHH", "HHW"));
Console.WriteLine(MatchToString("WWW", "WWW"));
Console.WriteLine(MatchToString("HHWH", "WWWW"));
//these are doesn't
Console.WriteLine(MatchToString("HHH", "HHK"));
Console.WriteLine(MatchToString("HHH", "HKK"));
Console.WriteLine(MatchToString("WWW", "ABC"));
Console.ReadLine();
}