Swift Regex with special Characters

13,079

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,}$"
Share:
13,079
Admin
Author by

Admin

Updated on June 18, 2022

Comments

  • Admin
    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
      Martin R about 6 years
    • Admin
      Admin about 6 years
      It'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
      rmaddy about 6 years
      Since 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
      Admin about 6 years
      You 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
    Admin about 6 years
    Ahh, escape the escape. Makes sense. Haha, it worked! Thanks!
  • Nicolas Miari
    Nicolas Miari almost 6 years
    Escapeception. Once again, @rmaddy saves the day :-)