Regex when placing DOS / Windows path
Implementing Quotation \Q and \E escape characters is probably the best approach. However, since the backslash is typically used as a DOS / Windows file delimiter, the sequence " \E " in the path can affect the pairing of \Q and \E When accounting for wildcard tokens * and ? this backslash situation can be resolved as follows:
Search: [^*?\\]+|(\*)|(\?)|(\\)
In the function of replacing the element βUse a simple exampleβ two new lines were added to accommodate a new search template. The code will still be Linux-friendly. As a method, it can be written as follows:
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(); }
The code to demonstrate the implementation of this method can be written as follows:
String s = "C:\\Temp\\Extra\\audio??2012*.wav"; System.out.println("Input: "+s); System.out.println("Output: "+wildcardToRegex(s));
These will 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
J. hanney
source share