Here is some code. This is the first time I have tried to write such a function, I'm sure the is a better way. I still think regular expressions will somehow play a part.
Notes on code:
- escapeRegex(String) is a function I wrote to escape meta characters in the input String.
Here is the part of the program dealing with the regex:
final Pattern pattern = Pattern.compile(patternBuffer.toString());
FilenameFilter filter = new FilenameFilter()
{
public boolean accept(File dir, String name)
{
if (pattern.matcher(name).matches())
{
return true;
}
return false;
}
};
searchResults = dir.listFiles(filter);
here is the entire function:
public static File[] wildcardFileSearch(File dir, String searchString, String wildcard)
{
File[] searchResults = null;
String beginString = null;
String endString = null;
ArrayList middleParts = new ArrayList();
boolean wildcardFirst = false, wildcardLast = false;
//check input
if (dir == null || !dir.exists() || !dir.isDirectory())
{
throw new IllegalArgumentException("Argument dir must be a directory that exists");
}
if (StringUtils.isEmpty(searchString) || StringUtils.isEmpty(wildcard))
{
throw new IllegalArgumentException("Arguments searchString and wildcard must be non-empty, non-null Strings");
}
//if there are no wild cards, do a basic search
if (searchString.indexOf(wildcard) == -1)
{
return fileSearch(dir, searchString);
}
//check special conditions: wildcard first or last char
if (searchString.startsWith(wildcard))
wildcardFirst = true;
if (searchString.endsWith(wildcard))
wildcardLast = true;
//divide file into pieces based on the wildcard
String[] searchParts = searchString.split(escapeRegex(wildcard));
int i = 0;
int stop = searchParts.length;
if (!wildcardFirst)
{
beginString = searchParts[0];
i = 1;
}
if (!wildcardLast)
{
endString = searchParts[searchParts.length - 1];
stop = searchParts.length - 1;
}
for (; i < stop; i++)
{
middleParts.add(searchParts[i]);
}
//complile patern
StringBuffer patternBuffer = new StringBuffer();
if (beginString != null)
{
patternBuffer.append("^(");
patternBuffer.append(escapeRegex(beginString));
patternBuffer.append(").");
patternBuffer.append("*");
}
else
{
patternBuffer.append(".*");
}
if (middleParts.size() > 0)
{
Iterator iter = middleParts.iterator();
while (iter.hasNext())
{
String element = (String) iter.next();
if (StringUtils.isEmpty(element))
continue;
patternBuffer.append("(");
patternBuffer.append(escapeRegex(element));
patternBuffer.append(")");
}
}
if (endString != null)
{
patternBuffer.append(".*");
patternBuffer.append("(");
patternBuffer.append(escapeRegex(endString));
patternBuffer.append(")$");
}
final Pattern pattern = Pattern.compile(patternBuffer.toString());
FilenameFilter filter = new FilenameFilter()
{
public boolean accept(File dir, String name)
{
if (pattern.matcher(name).matches())
{
return true;
}
return false;
}
};
searchResults = dir.listFiles(filter);
return searchResults;
}