How to remove non-digits from a String

5 years ago by in How To, Utilities Tagged: , ,

Using regular expressions we can remove any non-digits from a string as shown next

String text = "12 34 56";
String clean = text.replaceAll("[^\\d]", "" );

The regular expression [^\d] (not that this is regular expression and you need to escape the backslash when used in Java) matches with anything that is not a digit. The same expression can be used to split a given string.

Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 SearchSecurity.co.UK award (Website).

Leave a Comment


Time limit is exhausted. Please reload the CAPTCHA.