import Foundation
let pattern = #"^(([^<>()\[\]\.,;:\s@\"]{1,64}(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@\[*(?!.*?\.\.)(([^<>()[\]\.,;\s@\"]+\.?)+[^<>()[\]\.,;\s@\"]{2,})\]?"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = ##"""
prettyandsimple@example.com
very.common@example.com
disposable.style.email.with+symbol@example.com
other.email-with-dash@example.com
(one-letter local part)
x@example.com
"much.more unusual"@example.com
"very.unusual.@.unusual.com"@example.com
"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
example-indeed@strange-example.com
(local domain name with no TLD)
admin@mailserver1
#!$%&'*+-/=?^_`{}|~@example.org
"()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org
(space between the quotes)
" "@example.org
example@localhost
example@s.solutions
user@com
user@localserver
user@[2001:DB8::1][
user@[IPv6:2001:db8::1]
©other.email-with-dash@example.com
?prettyandsimple@example.com
用户@例子.广告
अजअय@डाअटा.भारत
квіточка@пошта.укр
θσερ@εχαμπλε.ψομ
Dörte@Sörensen.example.com
аджай@экзампл.рус
Invalid email addresses[edit]
(no @ character)
Abc.example.com
(only one @ is allowed outside quotation marks)
A@b@c@example.com
(none of the special characters in this local part are allowed outside quotation marks)
a"b(c)d,e:f;g<h>i[j\k]l@example.com
(quoted strings must be dot separated or the only element making up the local part)
just"not"right@example.com
(spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a backslash)
this is"not\allowed@example.com
(even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes)
this\ still\"not\\allowed@example.com
(double dot before @)
john..doe@example.com
with caveat: Gmail lets this through, Email address#Local-part the dots altogether
(double dot after @)
john.doe@example..com
(exceeds 64 characters in local part)
1234567890123456789012345678901234567890123456789012345678901234+x@example.com
alskjnakjanv1wadfqaebbsfdfagfbnbKJANDVlvn13dcljnvzlkjbnadlkgf3cjnj@winnipeg.com
"""##
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"QuestionText = "$1","#
let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)
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