首页 > 解决方案 > 使用 ant 替换字符串中的子字符串的正则表达式

问题描述

尝试在 ant 文件中使用正则表达式(使用 replaceregexp 标记)来替换 Java 类中不是常量的特定字符串时,我一直在苦苦挣扎,例如:
Replace: V1_0_0 by V2_0_0 In:

public void doSomething() {
    return "xxxxxxxV1_0_0.yyyyyyyy"
}

当然 V1_0_0 总是会改变 .yyyyyyyy 会改变,但 xxxxxxx 会一样

这是我能得到的更接近: (?<=xxxxxxx).* 或 (?<=xxxxxxx).*

但这就是我得到的:

public void doSomething() {
    return "xxxxxxxV2_0_0;
}

xxxxxxx 或 yyyyyyyy 可以是 java 类名中允许的任何字符

标签: javaregexant

解决方案


试试这样:

(?:xxxxxxx)V[0-9]+_[0-9]+_[0-9]+(?:\.[a-z]+)?

yyyyyy使用?. a-z也许您需要一个与, 也许[a-zA-Z]或不同的字符类[a-zA-Z0-9_]

演示

代码示例

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Ideone {
 public static void main(String[] args) throws java.lang.Exception {
  String regex = "(?:xxxxxxx)V[0-9]+_[0-9]+_[0-9]+(?:\\.[a-z]+)?";
  String string = "public void doSomething() {\n" 
                + "    return \"xxxxxxxV1_0_0.yyyyyyyy\";\n" 
                + "}";
  String subst = "xxxxxxxV2_0_0";

  Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
  Matcher matcher = pattern.matcher(string);

  String result = matcher.replaceAll(subst);
  System.out.println("Substitution result: " + result);
 }
}

推荐阅读