๐ฐ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]
Foundation โฉ NSString
Last updated