正则表达式Java替换
我有以下两个字符串:正则表达式Java替换,java,regex,Java,Regex,我有以下两个字符串: execute:13457689 74859374 execute这个词将来可能会更改,所以我的正则表达式应该可以处理它 public static void main(String... args) { replace("execute:13457689"); replace("74859374"); } private static void replace(String text) { System.out.print("input: "
execute:13457689
74859374
execute这个词将来可能会更改,所以我的正则表达式应该可以处理它
public static void main(String... args) {
replace("execute:13457689");
replace("74859374");
}
private static void replace(String text) {
System.out.print("input: " + text + ", ");
System.out.print("result: " + text.replaceFirst("(?<=(:|)).*$", "00000"));
System.out.println();
}
预期结果:
input: execute:13457689, result: execute:00000
input: 74859374, result: 00000
如何解决这个问题?试试这个正则表达式
(\w+:)\d+
以此作为替代
$10000
这里的技巧是使用
$1
,它表示组1捕获的字符串($2
表示组2,$3
表示组3,依此类推)。在这里,组1捕获一组单词字符,后跟:
您是否只想将任何数字字符串替换为5个零?是的,但如果前面有一个字符串,如execute:或handle:,我想保留该字符串。
$10000