1

Hello I am new to Swift, and I am working on a project that requires regex validation for email validation, here's the code

static func validateEmail(string: String?) -> Style.ValidationResult {

    guard let string = string else {
        return .init(
            isValid: false,
            error: ValidationErrors.noEmail
        )
    }

    let format = "^[^!-/[-_{-~]*(?:[0-9A-Za-z](?:[0-9A-Za-z]+|([.])(?!\1)))*([^!-/[-_{-~]){1,256}@[a-zA-Z0-9][a-zA-Z0-9-]{0,64}(\.[a-zA-Z0-9][a-zA-Z0-9-]{0,25})+"
    let predicate = NSPredicate(format: "SELF MATCHES %@", format)
    return .init(
        isValid: predicate.evaluate(with: string),
        error: ValidationErrors.noEmail
    )
}

When I build the app and actually test this part, it either returns Can't do regex matching, reason: Can't open pattern U_REGEX_MISSING_CLOSE_BRACKET or simply cannot build.

I am aware that this is due to the escape character, but I have tried many times and still couldn't find out how to solve it, can anyone tell me the rules to conver JavaScript regex to Swift regex

JetCat
  • 78
  • 1
  • 8

1 Answers1

2

You need to

  • Use a "raw" string literal to avoid double escaping backslashes that form regex escapes (you have \1 backreference and \. regex escape in the pattern), so use let format = #"..."#
  • You need to escape square brackets inside character classes in an ICU regex pattern because [ and ] are both special (they are used to create character class intersections and unions).

Thus, you need to use

let format = #"^[^!-/\[-_{-~]*(?:[0-9A-Za-z](?:[0-9A-Za-z]+|(\.)(?!\1)))*([^!-/\[-_{-~]){1,256}@[a-zA-Z0-9][a-zA-Z0-9-]{0,64}(?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,25})+"#
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563