Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip everything except digits from a string in Scala (quick one liners)

Tags:

filter

scala

This is driving me nuts... there must be a way to strip out all non-digit characters (or perform other simple filtering) in a String.

Example: I want to turn a phone number ("+72 (93) 2342-7772" or "+1 310-777-2341") into a simple numeric String (not an Int), such as "729323427772" or "13107772341".

I tried "[\\d]+".r.findAllIn(phoneNumber) which returns an Iteratee and then I would have to recombine them into a String somehow... seems horribly wasteful.

I also came up with: phoneNumber.filter("0123456789".contains(_)) but that becomes tedious for other situations. For instance, removing all punctuation... I'm really after something that works with a regular expression so it has wider application than just filtering out digits.

Anyone have a fancy Scala one-liner for this that is more direct?

like image 268
Zaphod Avatar asked May 19 '15 20:05

Zaphod


2 Answers

You can use filter, treating the string as a character sequence and testing the character with isDigit:

"+72 (93) 2342-7772".filter(_.isDigit) // res0: String = 729323427772
like image 113
Arne Claassen Avatar answered Oct 01 '22 08:10

Arne Claassen


You can use replaceAll and Regex.

"+72 (93) 2342-7772".replaceAll("[^0-9]", "") // res1: String = 729323427772

like image 43
Callum Avatar answered Oct 01 '22 09:10

Callum