0

The regex in kotlin does not allow white spaces, emojis etc. I want this regex to be used in swift but the regex does not work exactly and needs to be converted. I have tried but I am unable to achieve proper conversion. Help would be appreciated

Code tested in online kotlin playground

Kotlin Playground code:

import java.util.regex.*

fun main() {

    println(isValidEmailAddress(" abc@gmail.com"))
    // returns false
    println(isValidEmailAddress("abc@gmail.com"))
    // returns false

}

val EMAIL_PATTERN = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
            "\\@" +
            "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
            "(" +
                "\\." +
                "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
            ")+")

public fun isValidEmailAddress(email: String): Boolean {
        return EMAIL_PATTERN.matcher(email).matches()
    }

Code tested in online swift playground

Swift Playground code:

import Foundation

extension String {
    func isValidEmail() -> Bool {
        let regex = try! NSRegularExpression(pattern: "[a-zA-Z0-9+._%-+]{1,256}@[a-zA-Z0-9][a-zA-Z0-9-]{0,64}+\\.[a-zA-Z0-9][a-zA-Z0-9-]{0,25}+", options: .caseInsensitive)
        return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
    }
}

var str = " abc@gmail.com".isValidEmail()
print(str)
// returns true
str = "abc@gmail.com".isValidEmail()
print(str)
// returns true

Answer after following suggested changes:

import Foundation

extension String {
    func isValidEmail() -> Bool {
        let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9+._%-]{1,256}@[a-zA-Z0-9][a-zA-Z0-9-]{0,64}+(\\.[a-zA-Z0-9][a-zA-Z0-9-]{0,25})+$", options: .caseInsensitive)
        return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count)) != nil
    }
}

var str = " abcgmail.com".isValidEmail()
print(str)
// returns false
str = "ac@gmail.com".isValidEmail()
print(str)
// returns false

0 Answers0