0

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

3 Answers 3

2

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

fun checkForChars(string: String): Boolean = string.all(Char::isLetterOrDigit)
Sign up to request clarification or add additional context in comments.

Comments

1

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))
}

3 Comments

thanks for your help, that fixed the problem. but i didn't quite understand "\w*" pattern , i searched the web and found this "Matches the preceding element zero or more times." but still didn't understand, if u can explain i would be really grateful
"\w" if my string is 1 letter only?
\w matches 1 letter exactly, it will match only strings like "a", "b". Since your string can have zero or more letters you use the *. If you want to make sure that you have at least one letter then instead of * you put +
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.