Reputation: 99
I am trying to check if a string has all the forbidden characters like "/#$%^&" ... i tried to find a solution but couldn't find anything , i just want to check if all characters in the string match regex pattern \w
string.all seems perfect but i cant add regex pattern to it here is what i am trying to do:
// "abce#ios" must return false because it contains #
// "abcdefg123" must return true
fun checkForChars(string :String) :Boolean {
val pattern = "\\w".toRegex()
return (string.contains(regex = pattern))
}
thanks in advance
Upvotes: 0
Views: 106
Reputation: 323
You can use
Regex("[^/#$%^&]*").matches(string)
to check for the forbidden characters.
You can include any forbidden characters into a [^...]*
construction. Though a "
character would need to be screened and a \
character would need to be screened twice. Regex("[^\\\\/#$%^&\"]*")
.
For \\w*
regex you can use Regex("\\w*").matches(string)
Upvotes: 1
Reputation: 2554
You made several mistakes:
\w
pattern matches exactly one letter, if you want to match zero or more letters you need to change it to: \w*
The final solution is the following:
fun checkForChars(string :String) :Boolean {
val pattern = "\\w*".toRegex()
return (string.matches(pattern))
}
Upvotes: 1
Reputation: 8442
You don't need to use regex at all with all
:
fun checkForChars(string: String): Boolean = string.all(Char::isLetterOrDigit)
Upvotes: 2