Java:将regexp替换为已处理的匹配
假设我有以下字符串:Java:将regexp替换为已处理的匹配,java,regex,replace,Java,Regex,Replace,假设我有以下字符串: String in = "A xx1 B xx2 C xx3 D"; 我想要结果: String out = "A 1 B 4 C 9 D"; 我想用一种最类似于: String out = in.replaceAll(in, "xx\\d", new StringProcessor(){ public String process(String match){ int num = Integer.parseInt(ma
String in = "A xx1 B xx2 C xx3 D";
我想要结果:
String out = "A 1 B 4 C 9 D";
我想用一种最类似于:
String out = in.replaceAll(in, "xx\\d",
new StringProcessor(){
public String process(String match){
int num = Integer.parseInt(match.replaceAll("x",""));
return ""+(num*num);
}
}
);
也就是说,使用字符串处理器在执行实际替换之前修改匹配的子字符串
是否已经编写了一些库来实现这一点?使用
Matcher.appendReplacement()
:
你可以很容易地写自己。以下是如何:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegEx {
static public interface MatchProcessor {
public String processMatch(final String $Match);
}
static public String Replace(final String $Str, final String $RegEx, final MatchProcessor $Processor) {
final Pattern aPattern = Pattern.compile($RegEx);
final Matcher aMatcher = aPattern.matcher($Str);
final StringBuffer aResult = new StringBuffer();
while(aMatcher.find()) {
final String aMatch = aMatcher.group(0);
final String aReplacement = $Processor.processMatch(aMatch);
aMatcher.appendReplacement(aResult, aReplacement);
}
final String aReplaced = aMatcher.appendTail(aResult).toString();
return aReplaced;
}
static public void main(final String ... $Args) {
final String aOriginal = "A xx1 B xx2 C xx3 D";
final String aRegEx = "xx\\d";
final String aReplaced = Replace(aOriginal, aRegEx, new MatchProcessor() {
public String processMatch(final String $Match) {
int num = Integer.parseInt($Match.substring(2));
return ""+(num*num);
}
});
System.out.println(aReplaced);
}
}
希望这有帮助。太好了,真的忽略了这个方法!非常感谢。我不知道
appendReplacement
和appendTail
。非常感谢。的确,那很好。谢谢!:)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegEx {
static public interface MatchProcessor {
public String processMatch(final String $Match);
}
static public String Replace(final String $Str, final String $RegEx, final MatchProcessor $Processor) {
final Pattern aPattern = Pattern.compile($RegEx);
final Matcher aMatcher = aPattern.matcher($Str);
final StringBuffer aResult = new StringBuffer();
while(aMatcher.find()) {
final String aMatch = aMatcher.group(0);
final String aReplacement = $Processor.processMatch(aMatch);
aMatcher.appendReplacement(aResult, aReplacement);
}
final String aReplaced = aMatcher.appendTail(aResult).toString();
return aReplaced;
}
static public void main(final String ... $Args) {
final String aOriginal = "A xx1 B xx2 C xx3 D";
final String aRegEx = "xx\\d";
final String aReplaced = Replace(aOriginal, aRegEx, new MatchProcessor() {
public String processMatch(final String $Match) {
int num = Integer.parseInt($Match.substring(2));
return ""+(num*num);
}
});
System.out.println(aReplaced);
}
}