Posted at

iOS11 から正規表現で名前付きキャプチャが使える

More than 1 year has passed since last update.

いまさらですが、 NSTextCheckingResultrange(withName:) なる定義が追加されていたので試してみました。

https://developer.apple.com/documentation/foundation/nstextcheckingresult/2915200-range

func yearMonthDay(from target: String) -> (year: Int, month: Int, day: Int)? {

let pattern = "(?<year>\\d+)-(?<month>\\d+)-(?<day>\\d+)"
let regex = try! NSRegularExpression(pattern: pattern, options: [])

let nsTarget = target as NSString
let nsRange = NSRange(location: 0, length: nsTarget.length)
guard let result = regex.firstMatch(in: target, options: [], range: nsRange) else {
return nil
}
return (
Int(nsTarget.substring(with: result.range(withName: "year")))!,
Int(nsTarget.substring(with: result.range(withName: "month")))!,
Int(nsTarget.substring(with: result.range(withName: "day")))!
)
}

print(yearMonthDay(from: "2018-4-10"))
// Optional((year: 2018, month: 4, day: 10))