Kotlin Remove all non alphanumeric characters

I am trying to remove all non alphanumeric characters from a string.

I tried using replace() with a regex as followed:

var answer = answerEditText.text.toString()
Log.d("debug", answer)
answer = answer.replace("[^A-Za-z0-9 ]", "").toLowerCase()
Log.d("debug", answer)

D/debug: Test. ,replace

D/debug: test. ,replace

Why are the punctuation characters still present? How to get only the alphanumeric characters?


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


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"