How to replace all special characters except for underscore and numbers in java?
Matthew Martinez
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("-", "_"); 2 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)