import Foundation
let pattern = ##"""
[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
frankp@gmail.com
shannon.eee@gmail.com
franks&shannon@gmail.com
frank%ddd@gmail.com
frank@gmail$.com
frank@gmail_gmail.com
frank@gmail.research.com
joe@ggg.gg.cccc.com
joe..joe@gmail.com
/
https://stackoverflow.com/questions/5174171/fix-regular-expression-for-emails-to-not-allow-consecutive-periods/5174201#5174201
*To avoid matching two consecutive dots you can add a negative lookahead at the beginning of your regular expression:
/^(?!.*\.{2})[a-z0-9etc...
------------
It will fail to match if there are two consecutive periods anywhere in the string and it doesn't require any other modifications to your original regular expression.
However it seems a bad idea as your regular expression isn't correct in the first place. If you insist on using regular expressions to validate email addresses, try this:
*/
wilson..gmail.com
wilson.gmail.com
^(?!.*\.{2})/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
"""##
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