您好我正在尝试以正确的格式替换错误插入的货币金额,如果格式正确则必须无所事事,所以我写了这段代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegexReplace {
public static void main(String[] args) {
Pattern pattern = null;
Matcher matcher = null;
String regExp = "^([0-9]{2,3})\\.([0-9]{3})\\.([0-9]{2})$||^([0-9]{2,3})\\,([0-9]{3})([0-9]{2})$||^([0-9]{2,3})\\.([0-9]{3})([0-9]{2})$";
String replacement = "($1\\,$2\\.$3)";
String patternText[] = {"14.978.00", "14,97800", "14.97800", "14,978.00"};
pattern = Pattern.compile(regExp);
for(String text : patternText){
matcher = pattern.matcher(text);
System.out.println(text +" : " + matcher.matches());
String value = text;
if (value != null) {
value = pattern.matcher(value).replaceAll(replacement);
text = value;
System.out.println(text);
}
}
}
}
此代码的输出如下:
14.978.00 : true
14,978.00,.
14,97800 : true
,.1,.4,.,,.9,.7,.8,.0,.0,.
14.97800 : true
,.1,.4,..,.9,.7,.8,.0,.0,.
14,978.00 : false
,.1,.4,.,,.9,.7,.8,..,.0,.0,.
而预期的输出如下:
14.978.00 : true
14,978.00
14,97800 : true
14,978.00
14.97800 : true
14,978.00
14,978.00 : false
no changes
答案 0 :(得分:0)
这似乎有效。
Pattern pattern = Pattern.compile("^(\\d{2,3})[.,]?(\\d{3})[.,]?(\\d{2})$");
String replacement = "$1,$2.$3";
String[] samples = {"14.978.00", "14,97800", "14.97800", "14,978.00"};
for (String sample : samples) {
Matcher matcher = pattern.matcher(sample);
System.out.println(sample + "\t= " + matcher.replaceAll(replacement));
}