LoginSignup
8
7

More than 5 years have passed since last update.

Windows のワイルドカード文字列を正規表現に変換するメソッド

Last updated at Posted at 2012-10-26
//
public static Regex WildCardToRegex(string wildCard) {
    if (wildCard == null) {
        throw new ArgumentNullException("wildCard");
    }
    if (wildCard == "") {
        throw new ArgumentException("wildCard");
    }
    CheckInvalidPathChars(wildCard);    //  throws ArgumentException();

    StringBuilder sb = new StringBuilder();

    var splitResult = wildCard.Split(Win32Path.PathSeparator);
    Debug.Assert(splitResult.Length > 0);

    foreach (var separated in splitResult) {
        var temp = separated;

        temp = Regex.Replace(temp, @"([$^\|.{}\[\]()+\\])", @"\$1");
        temp = Regex.Replace(temp, @"\*", @".*");
        temp = Regex.Replace(temp, @"\?", @".");

        sb.AppendFormat("|(?:{0})", temp);
    }
    sb.Remove(0, 1);
    string pattern = @"\\(" + sb.ToString() + ")$";

    return new Regex(pattern, RegexOptions.IgnoreCase);
}
8
7
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
8
7