Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 453
Distwo Avatar asked Aug 29 '17 02:08

Distwo


People also ask

How do you remove non-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.

How do I remove characters from string Kotlin?

To remove first N characters from a String in Kotlin, use String. drop() method.

How do you remove non-alphanumeric characters from an empty string?

The approach is to use the String. replaceAll method to replace all the non-alphanumeric characters with an empty string.


1 Answers

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

like image 124
hasen Avatar answered Sep 29 '22 08:09

hasen