簡體   English   中英

用空格替換破折號和逗號

[英]Replacing dashes and commas in Java with spaces

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

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

replaceall(regex,String)方法采用regex。 您可以使用一條語句來做到這一點

String output= str.replaceAll("[-,]", "");

您可以嘗試:

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

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

忘記contains() 采用 :

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

O / P:

adsaadsasda

您當前的代碼如下所示

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

如您所見,所有情況都互斥,因為else if部分意味着您將能夠刪除-, 清除數據后,可以通過刪除else關鍵字並移動parse part來稍微改善它

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

但是,你甚至不應該檢查你的文字contains ,或者-擺在首位,因為它將使直到找到搜索字符,你穿越了您的字符串一次。 無論如何,您還需要使用replaceAll方法遍歷您的第二次,因此您可以將代碼更改為

remove , 
remove - 
parse

甚至更好

remove , OR - 
parse

由於replaceAll需要regex ,你可以寫- OR ,條件為-|,甚至是[-,] (使用字符類

replaceAll("-|,","")

但是,如果標題正確,則您可能不想通過將其替換為空字符串(而應替換為空格)來刪除這些字符

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM