Kotlin Remove all non alphanumeric characters

You need to create a regex, this can be done by str.toRegex() before calling replace

val string = "AsAABa3a35e8tfyz.a6ax7xe"
string = string.replace(("[^\\d.]").toRegex(), "")

result: 3358.67

In case you need to handle words W and spaces

var string = "Test in@@ #Kot$#lin   FaaFS@@#$%^&StraßeFe.__525448=="
    string = string.replace(("[^\\w\\d ]").toRegex(), "")
    println(string)

result: Test in Kotlin FaaFSStraeFe__525448


You need to create a regex object

var answer = "Test. ,replace"
println(answer)
answer = answer.replace("[^A-Za-z0-9 ]", "") // doesn't work
println(answer)
val re = Regex("[^A-Za-z0-9 ]")
answer = re.replace(answer, "") // works
println(answer)

Try it online: https://try.kotlinlang.org/#/UserProjects/ttqm0r6lisi743f2dltveid1u9/2olerk6jvb10l03q6bkk1lapjn


I find this to be much more succinct and maintainable. Could be that the previous answers were made before these extensions were added?

val alphaNumericString = someString.toCharArray()
   .filter { it.isLetterOrDigit() }
   .joinToString(separator = "")

The standard library of Kotlin is beautiful like this. Just use String.filter combined with Char.isLetterOrDigit, like this:

val stringToFilter = "A1.2-b3_4C"
val stringWithOnlyDigits = stringToFilter.filter { it.isLetterOrDigit() }
println(stringWithOnlyDigits) //Prints out "A12b34C"