import Foundation
let pattern = #"^[a-zA-Z0-9_\-\.~]{4,}@[a-zA-Z0-9_\-\.~]{3,6}\.[a-zA-Z]{2,4}$"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = ##"""
info@bvo.global
foo..bar+ddddd@baz.com
foo@bar.baz.com
.foo@bar.baz.com
foo.@bar.baz.com
foo-bar@baz.com
-foo-bar@baz.com
foo-bar-@baz.com
客服@买卖.商务
foo@bar.baz
foo@.bar.baz
foo@bar.baz.
foo@bar.baz
foo@bar.ba
foo@bar.baz.quux
foo@bar.b
foo@bar.bazquux
foo@031.33.7.255
42@255.255.255.255
42@199.1.1.1
42@256.255.255.255
foo@63-character-long-domain-name-which-is-allowed-by-the-standards.com
foo@64character-long-domain-name-which-isnt-allowed-by-the-standards.com
255-chà räçter-loñg-emà îl#%address!&with+-some_weird.!?character~combinations'in_it-just-to-fill-üp-the-address-léngth-to-get-to-the-255-character.limit.-This_is_really_starting_to_become_a_quite_long_email_address.-who_would_even_use_something_like_this?@foo.bar
short-address-with-illegal-character,in-it@foo.bar
256-character-long.-email#%address!&with+-some_weird.!?character~combinations'in_it-just-to-fill-up-the-address-length-to-get-to-the-255-character.limit.-This_is_really_starting_to_become_a_quite_long_email_address.-who_would_even_use_something_like_this?@foo.bar
foo@similarly-long-address-url.of-253-characters.long.which-is-still-allowed.within-the-standards.so-lets-just-fill-the-rest.of-this-253-character-long-address-with-lorem-ipsum.copypasta-filler-then.Lorem-ipsum-dolor-sit-amet.consectetur-adipiscing-elit.com
foo@similarly-long-address-urls.of-254-characters.long.which-is-not-allowed.within-the-standards.so-lets-just-fill-the-rest.of-this-254-character-long-address-with-lorem-ipsum.copy-pasta-fillers-then.Lorem-ipsum-dolor-sit-amet.consectetur-adipiscing-elit.com
"""##
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