2014-01-16 23 views
1

我得到的輸出是打印x的值,剩下的兩個println打印出空白行。這個replaceAll()有什麼問題?

1.234.567,89 



Process finished with exit code 0 

我在做什麼錯?

public class Dummy { 

    public static void main(String args[]) { 
     String x = "1.234.567,89 EUR"; 
     String e = " EUR"; 
     x = x.replaceAll(" EUR",""); 
     System.out.println(x); 
     x = x.replaceAll(".", ""); 
     System.out.println(x); 
     x = x.replaceAll(",","."); 
     System.out.println(x); 
      //System.out.println(x.replaceAll(" EUR","").replaceAll(".","").replaceAll(",",".")); 
    } 
} 
+1

使用'x = x.replaceAll(「[。]」,「」);'第一個參數是一個正則表達式。 –

+2

你究竟想要做什麼? –

回答

9

的問題是,x = x.replaceAll(".", "");替換每一個字符用"",因此你有第二replaceAll()後空x

請注意,replaceAll()方法的第一個參數是一個正則表達式。

它更改爲:

x = x.replaceAll("\\.", ""); 
3

String#replaceAll()方法需要一個正則表達式作爲第一參數。而正則表達式中的.匹配除換行符以外的任何字符。這就是它取代一切的原因。

您可以改爲使用String#replace()

x = x.replace(" EUR",""); 
System.out.println(x); 
x = x.replace(".", ""); 
System.out.println(x); 
x = x.replace(",","."); 
0

使用Pattern#quote

x = x.replaceAll(Pattern.quote("."), ""); 

告訴Java中.具有特殊意義的正則表達式.,但是字符串.

其他的解決方案:

  • 使用replace接受一個字符串
  • 逃離.通過\\.(轉義正則表達式是由\做,但在Java中\寫入\\
0

讀的JavaDoc來自String.replaceAll(String regex, String replacement)

正則表達式

  • 正則表達式到該字符串是要被匹配

The dot (.) matches (almost) any character.爲了躲避dot使用backslash\),Java需要雙反斜槓(\\)。

轉義點後的固定代碼如下所示。

public static void main(String args[]) { 
    String x = "1.234.567,89 EUR"; 
    String e = " EUR"; 
    x = x.replaceAll(" EUR",""); 
    System.out.println(x); 
    x = x.replaceAll("\\.", ""); 
    System.out.println(x); 
    x = x.replaceAll(",","."); 
    System.out.println(x);   
} 
1

使用

System.out.println(x.replaceAll(" EUR","").replaceAll("\\.","") 
               .replaceAll(",",".")); 

,而不是

System.out.println(x.replaceAll(" EUR","").replaceAll(".","") 
               .replaceAll(",",".")); 

你必須花葶.\\.

可以在單行做法如下

System.out.println(x.replaceAll(" EUR|\\.|,","")); 
0

作爲一種替代的解決方案:

考慮使用NumberFormat.getCurrencyInstanceDecimalFormat。 NumberFormat提供了一個parse方法。

E.g.嘗試:

final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.GERMANY); 
if (currencyFormat instanceof DecimalFormat) { 
    final DecimalFormat currencyDecimalFormat = (DecimalFormat) currencyFormat; 

    final DecimalFormatSymbols decimalFormatSymbols = currencyDecimalFormat.getDecimalFormatSymbols(); 
    decimalFormatSymbols.setCurrencySymbol("EUR"); 
    currencyDecimalFormat.setDecimalFormatSymbols(decimalFormatSymbols); 

    currencyDecimalFormat.setParseBigDecimal(true); 

    System.out.println(currencyFormat.format(new BigDecimal("1234567.89"))); 
    final BigDecimal number = (BigDecimal) currencyFormat.parse("1.234.567,89 EUR"); 
    System.out.println(number); 
}