Rishabh Jain
Rishabh Jain

Reputation: 297

Regex matches always returns false

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

Answers (2)

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

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions