JDK 7。 正则表达式处理 str1 并获取所有内部数字的平方的方法是什么?
String str1="ab cd 2 4 ef 12x";
...
System.out.println(str1.replaceAll("...", "..."));
我们可以将控制台输出为
ab cd 4 16 ef 144x
不使用循环?
也许它是如此复杂或不可能......不幸的是,我不知道。 预先感谢您。
最佳答案
不可能在一次或两次 replaceAll
调用中做到这一点,因为无法即时计算匹配的子字符串(您可以在 Perl 中执行此操作,但不能在 Java 中执行此操作)。
因此,正如我提到的,解决方法是在循环中使用 Matcher#appendReplacement
。
查看sample demo :
String s = "ab cd 2 4 ef 12x";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("\\d+").matcher(s);
while (m.find()) {
m.appendReplacement(result,
String.valueOf((int)Math.pow(Double.parseDouble(m.group(0)), 2))); // Calculate
}
m.appendTail(result);
System.out.println(result.toString());
关于java - 我们可以在没有循环语句的情况下计算字符串中的数字表达式(通过正则表达式)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35698073/