Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

How to replace all special characters except for underscore and numbers in java?

Writer 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 '_'.

4

This should fix it:

BusDetails=BusDetails.replaceAll("(\\W|^_)*", "");

The pattern (\\W|^_) matches any non-word character. Additionally it excludes _.

0
BusDetails=BusDetails.replaceAll("[^_0-9]+", "");

This retain integer numbers but not decimals (add a "." for that)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy