import Foundation
let pattern = #"(?<=\b)\w([\w\.\-_0-9])*(@| at )[\w0-9][\w\-_0-9]*((\.| DOT )[\w\-_0-9]+)+(?=\b)"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = ##"""
test@email.com
test-user@email.com
test.user@email.com
33test33@email.com
test99user-_22@email.com
test@e.mail
test@g.mail
test AT email.com
test AT email DOT com
test AT email dot com
test at email.com
test@email DOT com
this is not an email @twitterUser
this is just an an string el@
Valid
-------
first.last@iana.org
1234567890123456789012345678901234567890123456789012345678901234@iana.org
x@x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x2
1234567890123456789012345678901234567890123456789012345678@12345678901234567890123456789012345678901234567890123456789.12345678901234567890123456789012345678901234567890123456789.123456789012345678901234567890123456789012345678901234567890123.iana.org
user+mailbox@iana.org
customer/department@iana.org
customer/department=shipping@iana.org
cal(woo(yay)hoopla)@iamcal.com
cal(foo\@bar)@iamcal.com
cal(foo\)bar)@iamcal.com
first(Welcome to the ("wonderful" (!)) world of email)@iana.org
pete(his account)@silly.test(his host)
c@(Chris's host.)public.example
Invalid
---------
first@...........com
first.last@sub.do,com
first\@last@iana.org
first.last
.first.last@iana.org
first.last.@iana.org
"first"last"@iana.org
"""@iana.org
first\\@last@iana.org
Doug\ \"Ace\"\ Lovell@iana.org
()[]\;:,><@iana.org
test@.
test@[123.123.123.123
test@123.123.123.123]
"""##
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression