Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex doesn't change string

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading