LoginSignup
15
14

More than 5 years have passed since last update.

ワイルドカードを使用した文字列マッチ

Posted at

.Netの標準のライブラリにはワイルドカードを用いた文字列マッチは存在しない(と思う)ので、ワイルドカードを使用した文字列マッチをするには、ちょっとした変換が必要になります。
以下の通り、ワイルドカードの文字列を正規表現に変換してから正規表現の機能を用いて文字列マッチを行うのが良いと思います。

 using System.Text.RegularExpressions;
 //ワイルドカードの文字列を正規表現の文字列に変換する
 var regexPattern = System.Text.RegularExpressions.Regex.Replace(
   "ワイルドカードの文字列",
   ".",
   m =>
   {
     string s = m.Value;
     if(s.Equals("?")) {
       //?は任意の1文字を示す正規表現(.)に変換
       return ".";
     } else if(s.Equals("*")) {
       //*は0文字以上の任意の文字列を示す正規表現(.*)に変換
       return ".*";
     } else {
       //上記以外はエスケープする
       return System.Text.RegularExpressions.Regex.Escape(s);
     }
   }
   );

 //あとは以下のように正規表現の文字列として用いれば良い
 if(new Regex(regexPattern).IsMatch("regexPatternにマッチするか検査する文字列")) {
  }
15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14