nick isra
nick isra

Reputation: 99

Using string.all with regex

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

Answers (3)

Vitaly Roslov
Vitaly Roslov

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

Daniel
Daniel

Reputation: 2554

You made several mistakes:

  1. \w pattern matches exactly one letter, if you want to match zero or more letters you need to change it to: \w*
  2. Instead of checking whether the string contains the regex, you need to check if it matches the regex.

The final solution is the following:

fun checkForChars(string :String) :Boolean {
    val pattern = "\\w*".toRegex()
   return (string.matches(pattern))
}

Upvotes: 1

Andrei Tanana
Andrei Tanana

Reputation: 8442

You don't need to use regex at all with all:

fun checkForChars(string: String): Boolean = string.all(Char::isLetterOrDigit)

Upvotes: 2

Related Questions