我有正则表达式
private static final String COPY_NUMBER_REGEX = ".*copy(?<copy_num>\\d+)";
我需要按如下方式替换命名组:
private void setCopyNum(){
Pattern pa = Pattern.compile(COPY_NUMBER_REGEX);
Matcher ma = pa.matcher(template.getName());
if(ma.find()){
Integer numToReplace = Integer.valueOf(ma.group("copy_num")) + 1;
//How to replace the value of the original captured group with numToReplace?
}
}
问题实际上在评论中。 Java Regex中是否有允许我们替换命名组值的东西?我的意思是获得一个带有替换值的新String。例如:
input: Happy birthday template - copy(1)
output: Happy birthday template - copy(2)
答案 0 :(得分:1)
这是一个快速而肮脏的解决方案:
// | preceded by "copy"
// | | named group "copynum":
// | | | any 1+ digit
final String COPY_NUMBER_REGEX = "(?<=copy)(?<copynum>\\d+)";
// using String instead of your custom Template object
String template = "blah copy41";
Pattern pa = Pattern.compile(COPY_NUMBER_REGEX);
Matcher ma = pa.matcher(template);
StringBuffer sb = new StringBuffer();
// iterating match
while (ma.find()) {
Integer numToReplace = Integer.valueOf(ma.group("copynum")) + 1;
ma.appendReplacement(sb, String.valueOf(numToReplace));
}
ma.appendTail(sb);
System.out.println(sb.toString());
<强>输出强>
blah copy42
备注强>
copy_num
是一个无效的命名组 - 不允许使用下划线"(?<=copy\\()(?<copynum>\\d+)(?=\\))"