本文介绍了Kotlin删除所有非字母数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从字符串中删除所有非字母数字字符.
I am trying to remove all non alphanumeric characters from a string.
我尝试将replace()
与正则表达式一起使用,如下所示:
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/调试:测试. ,替换
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)
在线试用: https://try.kotlinlang.org/#/UserProjects/ttqm0r6lisi743f2dltveid1u9/2olerk6jvb10l03q6bkk1lapjn
这篇关于Kotlin删除所有非字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!