Regex doesn't change string

Advertisements

I want to remove all symbols that aren’t letters or numbers, but my string isn’t changed.

fun main() {
    var testStr = "Hello, World 2022!"
    countWords(testStr)
}
fun countWords(input: String) {

    val regex ="""^A-Za-z0-9""".toRegex()
    val inputChanged = input.replace(regex, " ")
    println("changed input: $inputChanged")

}

>Solution :

Your regular expression matches the string A-Za-z0-9 at the beginning of the input string.
Since your input string does not start with A-Za-z0-9, the regular expression does not match anything and no replacement is performed.

The regex you need is [^A-Za-z0-9].
This one matches any character that is not listed (^) in the character class ([...]).

fun main() {
    var testStr = "Hello, World 2022!"
    countWords(testStr)
}

fun countWords(input: String) {

    val regex ="""[^A-Za-z0-9]""".toRegex()
    val inputChanged = input.replace(regex, " ")
    println("changed input: |$inputChanged|")
}

The output:

changed input: |Hello  World 2022 |

I put pipes (|) around the modified string to be able to see the white space characters that replace the non-digit or non-letter characters at the boundaries of the input string.

Check it online.

Learn more about regular expressions at regular-expressions.info.
Use regex101.com to build and validate the regular expressions before using them in the code.


As a side note, the function is named countWords() but it does not count the words.
I guess this is because it is not ready yet, isn’t it?

Leave a ReplyCancel reply