2013-11-28 84 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)); 
}