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?
Non-alphanumeric characters can be remove by using preg_replace() function. This function perform regular expression search and replace. The function preg_replace() searches for string specified by pattern and replaces pattern with replacement if found.
To remove first N characters from a String in Kotlin, use String. drop() method.
The approach is to use the String. replaceAll method to replace all the non-alphanumeric characters with an empty string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With