用空格代替Java中的破折号和逗号
问题描述:
我正尝试使用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));
}
答
一个语句可以尝试使用:
String result = numOfViewsM.replaceAll("[-,]", "");
为replaceAll()
方法的第一个参数是一个正则表达式。
答
忘记。用途:
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
一部分,你会明确您的数据,如
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
// ^^^