I'd like to read through a user input string that removes all nondigit characters excluding some characters like +,-,/,. etc. This is for a calculator. Is there an easy way to do this or do I need to split the initial string beforehand.
You can use this. Add any characters you want to keep inside the [ ]
string.replaceAll("[^0-9+-]", "");
When you use ^
inside []
, it will match any character that is NOT in []
(excluding the ^
).
In this case, it will match any character that is not a number (from 0 to 9), not a +
, and not a -
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.