/*
 * [TestWildcard.java]
 *
 * Summary: demonstrates how to connvert a wildcard to a regex.
 *
 * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2009-04-08 initial release
 */
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;
                // chars that have magic regex meaning. They need quoting to be taken literally
                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 ] ) );
        }
    }