過去の Swift バージョンで記述したコードが Swift3.0 でコンパイルした際に警告を出力していたので書き直した.
簡単に個人的なメモ
– Swift は正規表現は,NSRange などを使用する必要があるため少し面倒.
– 正規表現を扱うには,NSRegularExpression インスタンスを使用する.
– 正規表現の検索結果を参照する必要がある場合,regex.matches を参照する.
– String クラスの characters.count は文字列の文字を,全角半角関係なく1文字と数える.
– NSString クラスの length は,全角文字を半角文字2文字分として数える.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import Foundation extension String { var count: Int { let string_NS = self as NSString return string_NS.length } // 正規表現で検索する. // .caseInsensitive 大文字小文字の区別を無視する func pregMatche(pattern: String, options: NSRegularExpression.Options = [.caseInsensitive]) -> Bool { guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else { return false } let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, self.count)) return matches.count > 0 } // 正規表現で検索する.(検索結果を使用) func pregMatche(pattern: String, options: NSRegularExpression.Options = [.caseInsensitive], matches: inout [String]) -> Bool { guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else { return false } let targetStringRange = NSRange(location: 0, length: self.count) let results = regex.matches(in: self, options: [], range: targetStringRange) for i in 0 ..< results.count { for j in 0 ..< results[i].numberOfRanges { let range = results[i].rangeAt(j) matches.append((self as NSString).substring(with: range)) } } return results.count > 0 } } |