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(" [email protected]"))
    // returns false
    println(isValidEmailAddress("a😃[email protected]"))
    // 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 = " [email protected]".isValidEmail()
print(str)
// returns true
str = "a😃[email protected]".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 = "a😃[email protected]".isValidEmail()
print(str)
// returns false
4
  • For a starter, using a string's count in NSRange is wrong and fails for emojis, compare stackoverflow.com/a/46294637/1187415 or stackoverflow.com/a/27880748/1187415. Commented Mar 16, 2020 at 7:41
  • 1
    The other error is that you have to anchor the pattern to the start and end of the string: pattern: "^.....$" Commented Mar 16, 2020 at 7:48
  • Thanks @MartinR for both the suggested changes. These solved the issue. Commented Mar 16, 2020 at 8:06
  • I think it's very likely that there's already a library available for Swift for this specific check. Commented Mar 16, 2020 at 8:19

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.