我有一个像这样的字符串"4 + 5 = 9;"
,我想为找到的每个号码添加一个。在Java 8中,Regex-replace-with-function-evaluation等价于什么?
我想为每个匹配使用正则表达式和转换函数。
我知道如何在Java中执行它< = 7.它在javadoc和this answer中。
我想知道是否有在Java中新的东西这个8
编辑: 这是我最好的尝试:
private static String regexTransform(String regex, String input,
Function<String, String> function) {
Matcher m = Pattern.compile(regex).matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, function.apply(m.group()));
}
m.appendTail(sb);
return sb.toString();
}
String res = regexTransform("[0-9]+", "4 + 5 = 9;", s-> String.valueOf(Long.parseLong(s) + 1));
System.out.println(res); // 5 + 6 = 10
看起来不像有在Java 8文档(http://download.java.net/jdk8/docs/api/java什么新的东西/util/regex/Matcher.html)。 – arshajii
看起来不错,认为它是正确的做法。 – aepurniet