4

I know I can write one myself, but I was hoping I can just reuse an existing one.

Ant-style globs are pretty much the same as normal file globs with the addition that '**' matches subdirectories.

FWIW, my implementation is:

public class AntGlobConverter {
    public static String convert(String globExpression) {
        StringBuilder result = new StringBuilder();

        for (int i = 0; i != globExpression.length(); ++i) {
            final char c = globExpression.charAt(i);

            if (c == '?') {
                result.append('.');
            } else if (c == '*') {
                if (i + 1 != globExpression.length() && globExpression.charAt(i + 1) == '*') {
                    result.append(".*");
                    ++i;
                } else {
                    result.append("[^/]*");
                }
            } else {
                result.append(c);
            }
        }

        return result.toString();
    }
}
Noel Yap
  • 18,822
  • 21
  • 92
  • 144

2 Answers2

1

It seems that you're trying to do something like this.

str.replace( /?/g, "." ).replace( /\*[^\*]/g, "[^/]*" ).replace( /\*\*/, ".*" );

If you can't use Ant Contrib, http://ant-contrib.sourceforge.net/tasks/tasks/propertyregex.html, then try this. This works for Java 1.6+.

<property name="before" value="This is a value"/>
<script language="javascript">
//<![CDATA[ 
    var before = project.getProperty("before");
    var result = before.replace( /?/g, "." ).replace( /\*[^\*]/g, "[^/]*" ).replace( /\*\*/, ".*" );
    project.setProperty("after", result);
//]]>       
</script>
<echo>after=${after}</echo>
Larry Battle
  • 9,008
  • 4
  • 41
  • 55
0

I recent came across this problem myself and wrote a method to do the conversion. To do it properly was more complicated than the code above in the question.

See the convertAntGlobToRegEx method in https://github.com/bndtools/bnd/blob/master/aQute.libg/src/aQute/libg/glob/AntGlob.java.

See https://github.com/bndtools/bnd/blob/master/aQute.libg/test/aQute/libg/glob/AntGlobTest.java for the test cases.

BJ Hargrave
  • 9,324
  • 1
  • 19
  • 27