9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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

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))
9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?