Swift Regex with special Characters
The problem is that characters [
, \
, and ]
need to be escaped because they have special meaning in a regular expression.
So you need \[
, \\
, and \]
in the regular expression. But since this is inside a Swift string, each \
needs to be escaped with a \
.
So [\]
becomes \[\\\]
in the regular expression which becomes \\[\\\\\\]
in the Swift string.
The final valid string is:
var passwordRegex = "^[A-Za-z0-9 !\"#$%&'()*+,-./:;<=>?@\\[\\\\\\]^_`{|}~].{8,}$"
Admin
Updated on June 18, 2022Comments
-
Admin almost 2 years
I am attempting to use this string:
var passwordRegex = "^[A-Za-z0-9 !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~].{8,}$"
As my regular expression pattern, but it keeps failing saying the pattern is invalid. I used the
\
character to escape for the characters:"
and\
, but it throws the error:invalid escape sequence in literal
for regex key characters like^ & [ ] | .
etc.What am I missing in order to allow the characters:
! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
(including space) in my regex? I assume it's something with how I am escaping, but I can't find anything anywhere for these characters in regards to SWIFT's regular expression.
-
Martin R about 6 yearsA useful method is
NSRegularExpression.escapedPattern(for:)
-
Admin about 6 yearsIt's pretty standard to limit the character's that are allowed in a password if you want to properly encrypt the password. Unless you plan to write an encryptor that handles every single possible character in the world (Chinese symbols, Arabic symbols, etc.)
-
rmaddy about 6 yearsSince you are going to be encrypting data obtained from the string, why does any particular character have anything to do with the ability to encrypt the password?
-
Admin about 6 yearsYou know, I’m not entirely for sure. But I do know it’s very common to limit what characters a user can use for a password. I dont know why you guys even care, you’re getting off topic now.
-
-
Admin about 6 yearsAhh, escape the escape. Makes sense. Haha, it worked! Thanks!
-
Nicolas Miari almost 6 yearsEscapeception. Once again, @rmaddy saves the day :-)