Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password regex not working in Kotlin

Tags:

kotlin

I am trying to run the below code to validate a password string against my regex. But it's always returning false. What am I doing wrong ?

fun main(args: Array<String>) {
     val PASSWORD_REGEX = """^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%!\-_?&])(?=\\S+$).{8,}""".toRegex()
    val password:String = "Align@123"
    println(PASSWORD_REGEX.matches(password))
}
like image 776
sagar suri Avatar asked Nov 18 '25 20:11

sagar suri


1 Answers

You are using raw strings but are escaping the last \S which is causing a literal match of \S. If I remove the extra backslash, your test case works for me. And as others have stated, you might be able to remove that stanza entirely.

So this...

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%!\-_?&])(?=\\S+$).{8,} 
                                                       ^
                                                       |
                                               Remove -+

Becomes this

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%!\-_?&])(?=\S+$).{8,}

I used Regex101 to help me, which seems to be a nice way to turn regex into English.

like image 77
Todd Avatar answered Nov 21 '25 15:11

Todd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!