How to remove everything except numbers from a string in Scala (fast single-line)

It drives me crazy ... there should be a way to cross out all non-digital characters (or do some other simple filtering) in String.

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

I tried "[\\d]+".r.findAllIn(phoneNumber)that Iteratee returns, and then I would have to recompile them into String somehow ... it seems terribly wasteful.

I also came up with: phoneNumber.filter("0123456789".contains(_)) but that gets tedious for other situations. For example, deleting all punctuation marks ... I'm really for something that works with a regular expression, so it has a wider application than just selecting numbers.

Does anyone have a fantastic one-line Scala for this more direct?

+4
source share
3 answers

You can use replaceAllregex as well.

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

+8
source

You can use filterit by treating the string as a sequence of characters and checking the character with isDigit:

"+72 (93) 2342-7772".filter(_.isDigit) // res0: String = 729323427772
+12
source

Another approach defining a set of valid characters, in this case

val d = '0' to '9'

etc. for val a = "+72 (93) 2342-7772", a filter to include a collection, for example, with any of them,

for (c <- a if d.contains(c)) yield c

a.filter(d.contains)

a.collect{ case c if d.contains(c) => c }
0
source

Source: https://habr.com/ru/post/1588876/


All Articles