Using eachDirMatch to Skip .svn Folders

I am writing a program that has to traverse a set of directories. Tried using the following code:

file.eachDirMatch (/.* [^. SVN] /) {// some code here}

But it didn't match any of my directories. I realize it boils down to the correct regex hanging by the head, but even after revising the Java Regular Expression documentation, I thought it should work.

+2


a source to share


4 answers


Try this regex:

/^(?!\.svn).*/

      



(This assumes that your linguistic regix flavor supports negative imagery.)

+2


a source


You can use any expression as a match, not just a regular expression:



file.eachDirMatch({ new File(it).name != ".svn" }) { dir -> println(dir.getPath()) }

      

+2


a source


Based on amber's answer, the whole thing looks like

file.eachDirMatch(~/^(?!\.svn).*/) { /* some code here */ }

      

For example, to filter out all hidden directories in the current directory, you can use

file('.').eachDirMatch(~/^(?!\.).*/) { dir ->
    println dir.getPath()
}

      

+2


a source


To the uninitiated (regex), this looks like gibberish. Why not just do

directories = []
file.eachDir() { File directory -> 
    if (directory.name != ".svn") {
      directories << directory
    }
}

      

Or if you want to ignore all hidden files:

directories = []
file.eachDir() { File directory -> 
    if (!directory.startsWith(".")) {
      directories << directory
    }
}

      

One-liners are great and all, but are now easy to read (and maintain presumably)

+1


a source







All Articles