package com.mindprod.example;
import static java.lang.System.*;
/**
* demonstrates how to connvert a wildcard to a regex.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2009-04-08 initial release
* @since 2009-04-08
*/
public class TestWildcard
{
/**
* convert a wild card containing * and ? to the equivalent regex
*
* @param wildcard wildcard string describing a file.
*
* @return regex string that could be fed to Pattern.comile
*/
private static String wildcardAsRegex( String wildcard )
{
StringBuilder sb = new StringBuilder( wildcard.length() * 110 / 100 );
for ( int i = 0; i < wildcard.length(); i++ )
{
final char c = wildcard.charAt( i );
switch ( c )
{
case '*':
sb.append( ".*?" );
break;
case '?':
sb.append( "." );
break;
case '$':
case '(':
case ')':
case '+':
case '-':
case '.':
case '[':
case '\\':
case ']':
case '^':
case '{':
case '|':
case '}':
sb.append( '\\' );
sb.append( c );
break;
default:
sb.append( c );
break;
}
}
return sb.toString();
}
/**
* @param args wildbard
*/
public static void main( String[] args )
{
if ( args.length != 1 )
{
err.println( "You must specify a wildcard on the command line." );
System.exit( 1 );
}
out.println( wildcardAsRegex( args[ 0 ] ) );
}
}