2015-04-02 166 views
0

我正嘗試使用Java中的replaceall函數刪除所有破折號( - )和逗號(,)。但是,我只能刪除短劃線或逗號。我怎樣才能解決這個問題?用空格代替Java中的破折號和逗號

if (numOfViewsM.find()){ 
        if (numOfViewsM.toString().contains(",")) 
        { 
         numOfViews =Integer.parseInt(numOfViewsM.group(1).toString().replaceAll(",", "")); 
        } 
        else if (numOfViewsM.toString().contains("-")) 
        { 
         numOfViews = Integer.parseInt(numOfViewsM.group(1).toString().replaceAll("-", "")); 
        } 
        else 
         numOfViews = Integer.parseInt(numOfViewsM.group(1)); 
       } 

回答

1

一個語句可以嘗試使用:

String result = numOfViewsM.replaceAll("[-,]", ""); 

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

1

忘記。用途:

public static void main(String[] args) { 
    String s = "adsa-,adsa-,sda"; 
    System.out.println(s.replaceAll("[-,]", "")); 
} 

O/P:

adsaadsasda 
1

您當前的代碼看起來像

if string contains , 
    remove , 
    parse 
else if string contains - 
    remove - 
    parse 
else 
    parse 

正如你看到的所有的情況下排除因else if一部分,這意味着你要麼是對方能夠刪除-,。你可以通過刪除else關鍵字和移動parse一部分,你會明確您的數據,如

if string contains , 
    remove , 
if string contains - 
    remove - 
parse 

但是,你甚至不應該檢查後提高了一點,如果你的文字contains,-擺在首位,因爲它會讓你遍歷你的字符串一次,直到找到搜索到的字符。您還需要無論如何與replaceAll方法來遍歷你的第二個時間,這樣你就可以改變你的代碼

remove , 
remove - 
parse 

甚至更​​好

remove , OR - 
parse 

由於replaceAll需要regex你可以寫-,條件爲-|,甚至[-,](使用character class

replaceAll("-|,","") 

但是,如果您的標題是正確的,您可能不想刪除這些字符,只需將它們替換爲空字符串,而是用空格

replaceAll("-|,"," "); //replace with space, not with empty string 
//    ^^^