使用正则表达式替换另一个正则表达式

时间:2013-11-28 18:45:01

标签: java regex

您好我正在尝试以正确的格式替换错误插入的货币金额,如果格式正确则必须无所事事,所以我写了这段代码:

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 

1 个答案:

答案 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));
}