java replaceall 捕获组_Java正则表达式替换为捕获组

资料来源:java-implementation-of-rubys-gsub

用法:

// Rewrite an ancient unit of length in SI units.

String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {

public String replacement() {

float inches = Float.parseFloat(group(1));

return Float.toString(2.54f * inches) + " cm";

}

}.rewrite("a 17 inch display");

System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a

// Regular Expression" example from the Java Almanac.

result = new Rewriter("([a-zA-Z]+[0-9]+)") {

public String replacement() {

return group(1).toUpperCase();

}

}.rewrite("ab12 cd efg34");

System.out.println(result);

实施(重新设计):

import static java.lang.String.format;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public abstract class Rewriter {

private Pattern pattern;

private Matcher matcher;

public Rewriter(String regularExpression) {

this.pattern = Pattern.compile(regularExpression);

}

public String group(int i) {

return matcher.group(i);

}

public abstract String replacement() throws Exception;

public String rewrite(CharSequence original) {

return rewrite(original, new StringBuffer(original.length())).toString();

}

public StringBuffer rewrite(CharSequence original, StringBuffer destination) {

try {

this.matcher = pattern.matcher(original);

while (matcher.find()) {

matcher.appendReplacement(destination, "");

destination.append(replacement());

}

matcher.appendTail(destination);

return destination;

} catch (Exception e) {

throw new RuntimeException("Cannot rewrite " + toString(), e);

}

}

@Override

public String toString() {

StringBuilder sb = new StringBuilder();

sb.append(pattern.pattern());

for (int i = 0; i <= matcher.groupCount(); i++)

sb.append(format("\n\t(%s) - %s", i, group(i)));

return sb.toString();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值