Using eachDirMatch to skip .svn folders
I'm writing a program which needs to traverse a set of directories. Tried to use the following code:开发者_如何学C
file.eachDirMatch(/.*[^.svn]/){ //some code here }
But that ended up match none of my directories. I realize this boils down figuring out the right regex hang head in shame but even after revisiting some Java Regular Expression documentation I thought this should work.
Try this regex instead:
/^(?!\.svn).*/
(This assumes that your language's regex flavor supports negative lookaheads.)
You can use any expression as matcher, not just regular expression:
file.eachDirMatch({ new File(it).name != ".svn" }) { dir -> println(dir.getPath()) }
Based on Amber answer, whole thing looks like
file.eachDirMatch(~/^(?!\.svn).*/) { /* some code here */ }
For example to filter out all those hidden dirs in current directory you can use
file('.').eachDirMatch(~/^(?!\.).*/) { dir ->
println dir.getPath()
}
To the uninitiated (to 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 do:
directories = []
file.eachDir() { File directory ->
if (!directory.startsWith(".")) {
directories << directory
}
}
One-liners are great and all, but now it's easy to read (and maintain presumably)
精彩评论