问题
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?
回答1:
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
回答2:
The standard library of Kotlin is beautiful like this. Just use String.filter combined with Char.isLetterOrDigit, like this:
val stringToFilter = "A1.2-b3_4C"
val stringWithOnlyDigits = stringToFilter.filter { it.isLetterOrDigit() }
println(stringWithOnlyDigits) //Prints out "A12b34C"
回答3:
I find this to be much more succinct and maintainable. Could be that the previous answers were made before these extensions were added?
val alphaNumericString = someString.toCharArray()
.filter { it.isLetterOrDigit() }
.joinToString(separator = "")
回答4:
You need to create a regex, this can be done by str.toRegex()
before calling replace
val string = "AsAABa3a35e8tfyz.a6ax7xe"
string = string.replace(("[^\\d.]").toRegex(), "")
result: 3358.67
In case you need to handle words W and spaces
var string = "Test in@@ #Kot$#lin FaaFS@@#$%^&StraßeFe.__525448=="
string = string.replace(("[^\\w\\d ]").toRegex(), "")
println(string)
result: Test in Kotlin FaaFSStraeFe__525448
回答5:
Kotlin thinks you substituting string, but not regex, so you should help a little bit to choose right method signature with regex as a first argument.
Use Regex type explicitly instead of string:
"[^A-Za-z0-9 ]".toRegex()
or tell that you are passing named regex parameter:
answer.replace(regex = "[^A-Za-z0-9 ]", "")
and in this case kotlin wont compile unless you pass real regex, not string
回答6:
You can try without regex, for example:
val ranges = ('0'..'9') + ('a'..'z') + ('A'..'Z')
val escaped = "1! at __ 2? at 345..0986 ZOk".filter { it in ranges }
回答7:
fun String.digitsOnly(): String{
val regex = Regex("[^0-9]")
return regex.replace(this, "")
}
fun String.alphaNumericOnly(): String{
val regex = Regex("[^A-Za-z0-9 ]")
return regex.replace(this, "")
}
Usage:
val alphaNumeric = "my string #$".alphaNumericOnly()
回答8:
I think it's easiest way:
fun String.toNumericString() = this.filter { it.isDigit() }
来源:https://stackoverflow.com/questions/45929687/kotlin-remove-all-non-alphanumeric-characters