Regex matches always returns false

Rishabh Jain

I'm trying to validate user input so that the only allowed characters in a string are A-Z, a-z, _, - and whitespace. To do that I wrote the following code:

val regex = Regex("[\\w\\s-]")
val flag = regex.matches("Hello Overlay")

But the value of flag is false and I can't figure out why.

Wiktor Stribiżew

To match the whole string meeting a pattern use

val regex = Regex("[\\w\\s-]+")

Or, to avoid overescaping:

val regex = Regex("""[\w\s-]+""")

See the Kotlin demo. Note that matches requires a full string match, but [\w\s-] only matches a single character.

val regex = Regex("""[\w\s-]+""")
val flag = regex.matches("Hello Overlay")
println(flag)  // => true

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at


Login to comment