将两个字符串与替换字符匹配

时间:2019-08-09 10:58:14

标签: c#

想象一个赌博游戏,您必须匹配所有三个单词才能获得奖励。

因此,如果您获得HHH,则会获得奖励。

我希望能够用W来模仿任何字母。

例如:

HWW = HHH  

HHW = HHH

但是

WWW = WWW

我该怎么做?

1 个答案:

答案 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();
}