🔰Regex
Swift ⟩ Regex
// NSRegularExpression, NSString.range(of:)
import Foundation
// One or more characters followed by an "@",
// then one or more characters followed by a ".",
// and finishing with one or more characters
let emailPattern = #"^\S+@\S+\.\S+$"#
// Matching Examples
// user@domain.com
// firstname.lastname-work@domain.com
// ----------- method 1: string.range() -------------
// ⭐️ 1. string.range()
let range = "test@test.com".range(
    of: emailPattern,
    options: .regularExpression
)
// range: Range<String.Index>?
// ----------- method 2: regex.matches() -------------
// ⭐️ 2.1 NSRegularExpression
let emailRegex = try! NSRegularExpression(
    pattern: emailPattern, options: []
)
// ⭐️ 2.2 NSRange
let source = "test@test.com"
let sourceRange = NSRange(
    source.startIndex ..< source.endIndex,
    in: source
)
// ⭐️ 2.3 regex.matches()
let matches = emailRegex.matches(
    in: source,
    options: [],
    range: sourceRange
)
// matches: [NSTextCheckingResult]
Last updated
Was this helpful?