4
5

More than 3 years have passed since last update.

【Swift】正規表現で含有判定

Last updated at Posted at 2020-08-13

文字列を含んでいるのか

  • 正規表現パターン:patternを引数で渡し、含んでいるのか評価した結果をtrue/falseで返します。
  • エラーがthrowされた場合、正規表現が間違えています
extension String {
    func contain(pattern: String) -> Bool {
        guard let regex = try? NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options()) else {
            return false
        }
        return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, self.count)) != nil
    }
}

利用方法

実装

print("apple".contain(pattern: "a.*e"))
print("apple".contain(pattern: String()))
print("".contain(pattern: String()))

出力

true
false
false

参考

4
5
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
4
5