Alex Rivera | Logout

Extract digits from a string in Java

Asked 2010-10-27T07:41:35.977
231

I have a Java String object. I need to extract only digits from it:

"123-456-789" -> "123456789"

Is there a library function that extracts only digits?

Thanks for the answers. Before I try these I need to know if I have to install any additional llibraries?

Edit
Report

1 Answer

24

Using Google Guava:

CharMatcher.inRange('0','9').retainFrom("123-456-789")

UPDATE:

Using Precomputed CharMatcher can further improve performance

CharMatcher ASCII_DIGITS=CharMatcher.inRange('0','9').precomputed();  
ASCII_DIGITS.retainFrom("123-456-789");
answered 2010-10-27T10:35:33.717

Your Answer