2015-04-02 139 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 
//    ^^^ 
相关问题