How to Replace All Special Characters Except for Underscore and Numbers in Java?
I Want to Replace All Special Characters from the String Object Busdetails Below with a Blank "" Except for _(Underscore) and Numbers in Java?...
I want to replace all special characters from the string object BusDetails below with a blank "" except for _(underscore) and numbers in java ?
BusDetails=BusDetails.replaceAll("—", "").replaceAll("\\s+","_").replaceAll("ROUTE", "BUS").replaceAll("-", "_");
3 Answers
BusDetails = BusDetails.replaceAll("[^a-zA-Z0-9_-]", "");
Using the regex pattern "[^a-zA-Z0-9_-]" we can replace all special characters (symbols) from the string except letters, numbers and '_'.
This should fix it:
BusDetails=BusDetails.replaceAll("(\\W|^_)*", "");
The pattern (\\W|^_) matches any non-word character. Additionally it excludes _.
BusDetails=BusDetails.replaceAll("[^_0-9]+", "");
This retain integer numbers but not decimals (add a "." for that)