Reputation: 297
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.
Upvotes: 1
Views: 1147
Reputation: 21
val regex = Regex("""[\w\s-]+""")
val flag = regex.matches("Hello Overlay")
println(flag) // => true
Upvotes: 0
Reputation: 627103
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
Upvotes: 2