我有一个字符串,例如:"2E6 3.34e-5 3 4.6"
并且我想使用 replaceAll 替换标记,例如:
"((\\-)?[0-9]+(\\.([0-9])+)?)(E|e)((\\-)?[0-9]+(\\.([0-9])+)?)"
(即两个数字之间有 e 或 E)转换成等效的正常数字格式(即"2E6"
用"2000000"
和"3.34e-5"
替换"0.0000334"
)
我写:
value.replaceAll("((\\-)?[0-9]+(\\.([0-9])+)?)(E|e)((\\-)?[0-9]+(\\.([0-9])+)?)", "($1)*10^($6)");
但我想实际上将第一个参数乘以 10 到第二个参数的幂,而不仅仅是这样写.. 有什么想法吗?
更新
根据您的建议,我做了以下操作:
Pattern p = Pattern.compile("((\\-)?[0-9]+(\\.([0-9])+)?)(E|e)((\\-)?[0-9]+(\\.([0-9])+)?)");
Matcher m = p.matcher("2E6 3.34e-5 3 4.6");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "WHAT HERE??"); // What HERE ??
}
m.appendTail(sb);
System.out.println(sb.toString());
更新
最后,这就是我所达到的:
// 32 #'s because this is the highest precision I need in my application
private static NumberFormat formatter = new DecimalFormat("#.################################");
private static String fix(String values) {
String[] values_array = values.split(" ");
StringBuilder result = new StringBuilder();
for(String value:values_array){
try{
result.append(formatter.format(new Double(value))).append(" ");
}catch(NumberFormatException e){ //If not a valid double, copy it as is
result.append(value).append(" ");
}
}
return result.toString().substring(0, result.toString().length()-1);
}