Wildcard matching in Java

前端 未结 6 1880
渐次进展
渐次进展 2020-12-14 23:13

I\'m writing a simple debugging program that takes as input simple strings that can contain stars to indicate a wildcard match-any

*.wav  // matches 

        
6条回答
  •  离开以前
    2020-12-14 23:33

    Regex While Accommodating A DOS/Windows Path

    Implementing the Quotation escape characters \Q and \E is probably the best approach. However, since a backslash is typically used as a DOS/Windows file separator, a "\E" sequence within the path could effect the pairing of \Q and \E. While accounting for the * and ? wildcard tokens, this situation of the backslash could be addressed in this manner:

    Search: [^*?\\]+|(\*)|(\?)|(\\)

    Two new lines would be added in the replace function of the "Using A Simple Regex" example to accommodate the new search pattern. The code would still be "Linux-friendly". As a method, it could be written like this:

    public String wildcardToRegex(String wildcardStr) {
        Pattern regex=Pattern.compile("[^*?\\\\]+|(\\*)|(\\?)|(\\\\)");
        Matcher m=regex.matcher(wildcardStr);
        StringBuffer sb=new StringBuffer();
        while (m.find()) {
            if(m.group(1) != null) m.appendReplacement(sb, ".*");
            else if(m.group(2) != null) m.appendReplacement(sb, ".");     
            else if(m.group(3) != null) m.appendReplacement(sb, "\\\\\\\\");
            else m.appendReplacement(sb, "\\\\Q" + m.group(0) + "\\\\E");
        }
        m.appendTail(sb);
        return sb.toString();
    }
    

    Code to demonstrate the implementation of this method could be written like this:

    String s = "C:\\Temp\\Extra\\audio??2012*.wav";
    System.out.println("Input: "+s);
    System.out.println("Output: "+wildcardToRegex(s));
    

    This would be the generated results:

    Input: C:\Temp\Extra\audio??2012*.wav
    Output: \QC:\E\\\QTemp\E\\\QExtra\E\\\Qaudio\E..\Q2012\E.*\Q.wav\E
    

提交回复
热议问题