com.izforge.izpack.compiler.util.AntPathMatcher Maven / Gradle / Ivy
package com.izforge.izpack.compiler.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* PathMatcher implementation for Ant-style path patterns. Examples are provided below.
*
* Part of this mapping code has been kindly borrowed from Apache Ant.
*
*
The mapping matches URLs using the following rules:
- ? matches one character
- * matches zero
* or more characters
- ** matches zero or more 'directories' in a path
*
* Some examples:
*
* bin/t?st.exe
- matches bin/test.exe
but also bin/tast.exe
* or bin/txst.exe
* bin/*.exe
- matches all .exe
files in the bin
directory
* bin/**/test.exe
- matches all test.exe
files underneath the bin
path
*
*/
public class AntPathMatcher {
private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{([^/]+?)\\}");
/**
* Match the given path
against the given pattern
,
* according to this PathMatcher's matching strategy.
* @param pattern the pattern to match against
* @param path the path String to test
* @param caseInsensitive whether the test should be case-insensitive
* @return true
if the supplied path
matched,
* false
if it didn't
*/
public boolean match(String pattern, String path, boolean caseSensitive) {
pattern = pattern.replaceAll("\\\\", "/");
pattern = pattern.replaceAll("\\.", "\\\\.");
pattern = pattern.replaceAll("\\*", "[^/]*");
pattern = pattern.replaceAll("(\\[\\^/\\]\\*){2}", ".*");
Matcher m = VAR_PATTERN.matcher(pattern);
StringBuffer s = new StringBuffer();
while (m.find()) {
m.appendReplacement(s, "\\\\Q\\$\\{"+m.group(1)+"\\}\\\\E");
}
m.appendTail(s);
int flags = 0;
if (!caseSensitive)
{
flags |= Pattern.CASE_INSENSITIVE;
}
Pattern p = Pattern.compile(s.toString(), flags);
return p.matcher(path).matches();
}
}