用正则表达式过滤文件名 [英] Filter file name with regex

查看:498
本文介绍了用正则表达式过滤文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果有更简单的类似Gradle的方式,如何列出目录中的文件但只有匹配正则表达式的文件。目前我的解决方案看起来像这样

  File fileList = file($ {moduleDir} / target)
/ / pattern for maven artifact
def pattern =〜^。* - [0-9] \\。[0-9] \\。[0-9]( - SNAPSHOT)?\ \.jar\ $
fileList.listFiles()。each {file - >
if(file.isFile()){
if(pattern.matcher(file.getName())){
copy {
from file.getPath()
into targetDir




code


我正在寻找的是完全绕过手动模式匹配。你知道任何可能帮助我实现这一目标的方法吗?

解决方案


我正在寻找的是完全绕过手动模式匹配


不太清楚您的意思,因为您显然希望匹配自定义模式。在任何情况下,我都会使用 Copy 任务而不是 copy 方法,并在 复制操作。例如:

 任务copyArtifacts(类型:复制){
from(fileTree(fileList).files){/ / flattening
include {
it.file.name ==〜^。* - [0-9] \\。[0-9] \\。[0-9] (-SNAPSHOT)?\\.jar\ $
}
}
into targetDir
}

PS:这些是你自己的工件吗?我问,因为一般来说,Maven工件可以使用几乎任何版本号格式。


I was wondering, if there's simpler "Gradle-like" way, how to list files in directory BUT ONLY those, matching regular expression. Currently my solution looks something like this

File fileList = file("${moduleDir}/target")
// pattern for maven artifact
def pattern = ~"^.*-[0-9]\\.[0-9]\\.[0-9](-SNAPSHOT)?\\.jar\$"
fileList.listFiles().each { file ->
    if (file.isFile()) {
        if (pattern.matcher(file.getName())) {
            copy {
                from file.getPath()
                into targetDir
            }
        }
    }
}

What I'm looking for, is to completely bypassing of manual pattern matching. Are you aware of any method that might help me to achieve this? Thanks.

解决方案

What I'm looking for, is to completely bypassing of manual pattern matching

Not quite sure what you mean by that, as you apparently want to match a custom pattern. In any case, I'd use a Copy task instead of the copy method, and would do the filtering "within" the copy operation. Something like:

task copyArtifacts(type: Copy) {       
    from(fileTree(fileList).files) { // flattening
        include {
            it.file.name ==~ "^.*-[0-9]\\.[0-9]\\.[0-9](-SNAPSHOT)?\\.jar\$"
        }
    }
    into targetDir
}

PS: Are these your own artifacts? I'm asking because in general, a Maven artifact can use pretty much any version number format.

这篇关于用正则表达式过滤文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆