You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gradle copySpec:如何针对正则表达式模式使用replaceToken?

Gradle Copy任务实现正则表达式替换的可行方案

由于ReplaceTokens仅支持固定字符串的令牌替换,不支持正则匹配,以下是几个直接可用的实现方法:

方法一:自定义FilterReader过滤器

通过自定义FilterReader实现逐行正则替换,灵活性最高:

task myTask(type: Copy) {
    from "/path/to"
    include "*.txt"
    into "/path/to/destination" // 必须指定输出目录

    filter { reader ->
        new FilterReader(reader) {
            private final Pattern regexPattern = Pattern.compile("Hello(.+)World")
            private final BufferedReader bufferedReader = new BufferedReader(reader)

            @Override
            String readLine() throws IOException {
                String line = bufferedReader.readLine()
                if (line != null) {
                    // 替换逻辑可按需调整,$1引用正则分组内容
                    line = line.replaceAll(regexPattern.pattern(), "NewPrefix$1NewSuffix")
                }
                return line
            }
        }
    }
}

方法二:调用Ant的replaceregexp任务

借助Gradle对Ant任务的原生支持,快速实现正则替换:

task myTask(type: Copy) {
    from "/path/to"
    include "*.txt"
    into "/path/to/destination"

    // 先完成文件复制,再对目标文件执行正则替换
    doLast {
        ant.replaceregexp(
            match: "Hello(.+)World",
            replace: "NewPrefix\\1NewSuffix", // Ant中分组引用需用\\转义
            flags: "g", // 开启全局替换
            byline: true // 逐行处理文本
        ) {
            fileset(dir: destinationDir, includes: "*.txt")
        }
    }
}

方法三:Groovy闭包简化实现

利用Groovy的语法特性,用极简代码完成替换:

task myTask(type: Copy) {
    from "/path/to"
    include "*.txt"
    into "/path/to/destination"

    filter { line ->
        // 直接对每行文本执行正则替换,$1引用分组内容
        line.replaceAll(/Hello(.+)World/, "NewPrefix$1NewSuffix")
    }
}

内容的提问来源于stack exchange,提问作者eastwater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 00:44:56