2009-06-05 5 views

답변

0

그러나 그것은 정규식과 중복 사소한 :

public static bool PathMatchSpec(String path, String spec) 
{ 
    String specAsRegex = Regex.Escape(spec).Replace("\\*", ".*").Replace("\\?", ".") + "$"; 
    return Regex.IsMatch(path, specAsRegex); 
} 

는 분명히 이것은들을 System.Text.RegularExpression 네임 스페이스 참조 가정합니다. 동일한 사양으로이 작업을 수행하려는 경우 Regex도 캐시 할 수 있습니다.

편집 추가 : P/Invoke는 실제로 옵션이지만 PathMatchSpec의 서명은 ANSI 문자열을 사용한다는 것을 나타내므로 각 호출에 대한 문자 집합 변환이 발생합니다. 그 길로 가면 명심하십시오. 이 경우 PathMatchSpecEx이 더 바람직 할 것입니다. 한마디로

+0

쿨 ... Escape() 메서드에 대해 몰랐습니다.) 내 솔루션의 일부를 명확하게 단순화 할 것이다;) – jerryjvl

0

... 나는의 ... 알고하지만 어쩌면이 함께 당신을 도울 수 (당신이 원하는 것보다 조금 더 긴 노트,하지만 나를 잘 역임했다)하지 않는 것이 :

sealed public class WildcardMatch 
{ 
    private static Regex wildcardFinder = new Regex(@"(?<wildcards>\?+|\*+)", RegexOptions.Compiled | RegexOptions.Singleline); 
    private Regex wildcardRegex; 

    public WildcardMatch(string wildcardFormat) : this(wildcardFormat, false) { } 

    public WildcardMatch(string wildcardFormat, bool ignoreCase) 
    { 
     if (wildcardFormat == null) 
      throw new ArgumentNullException("wildcardFormat"); 

     StringBuilder patternBuilder = new StringBuilder("^"); 
     MatchCollection matches = this.wildcardFinder.Matches(wildcardFormat); 
     string[] split = this.wildcardFinder.Split(wildcardFormat); 
     for (int ix = 0; ix < split.Length; ix++) 
     { 
      // Even indexes are literal text, odd indexes correspond to matches 
      if (ix % 2 == 0) 
       patternBuilder.Append(Regex.Escape(split[ix])); 
      else 
      { 
       // Matches must be substituted with Regex control characters 
       string wildcards = matches[ix/2].Groups["wildcards"].Value; 
       if (wildcards.StartsWith("*", StringComparison.Ordinal)) 
        patternBuilder.Append("(.*)"); 
       else 
        patternBuilder.AppendFormat(CultureInfo.InvariantCulture, "({0})", wildcards.Replace('?', '.')); 
      } 
     } 
     patternBuilder.Append("$"); 

     this.wildcardRegex = new Regex(
      patternBuilder.ToString(), 
      RegexOptions.Singleline | (ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None)); 
    } 

    public bool IsMatch(string value) 
    { 
     if (value == null) 
      return false; 

     return this.wildcardRegex.IsMatch(value); 
    } 

    public IEnumerable<string> ExtractMatches(string value) 
    { 
     if (value == null) 
      yield break; 

     Match match = this.wildcardRegex.Match(value); 
     if (!match.Success) 
      yield break; 

     for (int ix = 1; ix < match.Groups.Count; ix++) 
      yield return match.Groups[ix].Value; 
    } 
} 
+0

anelsons 'Regex.Escape()'를 사용하여 이스케이프 코드를 확실히 단순화 할 수 있습니다. – jerryjvl

관련 문제