我期待删除字符串中包含的任何数字(带小数)
对于Ex:
输入:“该游戏获得的Xbox 360版本的平均评论分数为96.92%和98/100。”
输出: - “游戏收到的平均评价分数为%和/或Xbox版本。”
我使用正则表达式实现了这一点。但是,我的语法也删除了字符串末尾的句点。
代码:
if(token.matches(".*\\d.*")) {
String s7=token.replaceAll("[0-9,.]", "");
s7=s7.replaceAll("( )+", " ");
stream.set(s7);
}
答案 0 :(得分:1)
尝试使用正则表达式:
\b\d+([.,]\d+)*\b
有关此正则表达式的说明,请参阅http://rick.measham.id.au/paste/explain.pl?regex=%5Cb%5Cd%2B%28%5B.%2C%5D%5Cd%2B%29 *%5Cb。
e.g:
public static void main(String[] args) {
String input = "The game received average review scores of 96.92% and 98/100 for the Xbox 360 version.";
System.out.println(
input.replaceAll("\\b\\d+([.,]\\d+)*\\b", "")
); // prints "The game received average review scores of % and / for the Xbox version."
}
答案 1 :(得分:0)
试试这个正则表达式(\d|\.)+
,这将匹配数字(包括小数点),然后用“”替换匹配的组
试试这个。
String str="The game received average review scores of 96.92% and 98/100 for the Xbox 360 version";
Pattern pattern = Pattern.compile("(\d|\.|,)+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
str=str.replace(matcher.group(),"");
}