Kotlin Remove all non alphanumeric characters

Distwo picture Distwo · Aug 29, 2017 · Viewed 31.8k times · Source

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?

Answer

hasen picture hasen · Aug 29, 2017

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