简体   繁体   English

如何过滤掉字符串中的所有字母,但不是所有特殊字符

[英]How to filter out all letters but not all special characters in a string

I am writing a program for my Java class that is supposed to raise 2 to whatever power the user puts in and is to terminate when the user enters -1. 我正在为我的Java类编写一个程序,该程序应该将用户施加的能力提高2,并在用户输入-1时终止。 The raising to the power and everything like that works, but the code I have to filter out letters also filters out special characters. 提升功能以及类似的功能都可以,但是我必须过滤掉字母的代码也可以过滤掉特殊字符。 Any suggestions? 有什么建议么?

Here is the code the filters out the characters: 以下是过滤掉字符的代码:

inputString = inputString.replaceAll("[^\\d.]", "");

Try following code and let me know, 尝试使用以下代码,让我知道,

inputString = inputString.replaceAll("[^-?0-9]","");

The regex used is: [^-?0-9] which means: 使用的正则表达式为: [^-?0-9]表示:

replace any character other than - (minus) or digits . 替换- (减号)或digits以外的任何字符。 You don't have to worry about + sign 您不必担心+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM