2013-11-28 89 views
0

你好,我是想取代正确的格式,如果错误地插入货币金额的格式是否正确是必须做什么,所以我写了这个代码:使用正则表达式与另一个正则表达式替换

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

虽然我确定可以在这里使用正则表达式,但我会假设'DecmalFormat'更容易用于格式化输出。 – FrankPl

+0

你的正则表达式很少有问题。首先你使用'a || b'这意味着'a'或'emptyString“''或'b'。如果你想说'a'或'b',那么使用单管如'a | b'。同样在你的正则表达式中,你使用'($ 1 \\,$ 2 \\。$ 3)'作为替换,但组1只存在于你的正则表达式的第一种情况。第一个'|'之后的组被索引4,5,6并且在另一个'|'7,8,9之后。 – Pshemo

回答

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