kotlinkotlin-android-extensions

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?


Solution

  • 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