当我尝试在ant文件中使用正则表达式(使用replaceregexp标签)来替换java类中的特定字符串(不是常量)时,我一直在努力,例如:
替换:V1_0_0 为 V2_0_0
在:
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 类名中允许的任何字符
最佳答案
尝试这样:
(?: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);
}
}
关于java - 使用 ant 替换字符串中的子字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747730/