13
16

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.

Swiftの正規表現は面倒くさい!

Last updated at Posted at 2015-12-16

#対象
 swiftの正規表現は面倒くさい!
 でも、ライブラリを導入するのも面倒くさい!
 コードは汚くてもいいからとにかく動くやつを!
 そんな物臭な方。

#環境
-Xcode 7.01
-Swift

#使い方と出力例

//Stringの拡張クラスとして提供

//Matchメソッド
// 出力は["一致パターン全文","グループ1","2"...]
"http://goowa.jp".Match("([a-zA-Z0-9]*)://(.*)")
// -> ["http://goowa.jp","http","goowa.jp"]


//Matchesメソッド
// 出力は["一つ目の一致パターン全文","グループ1","2"...]
//      ["二つ目の一致パターン全文","グループ1","2"...]
"むかしむかしあるところに".Matches("むかし")
// -> [["むかし"]["むかし"]]

#コード

StringEX.swift
    /**
     正規表現で検索を行う
     - parameter pattern:検索パターン
     - returns: [String]で検索結果を返す.
    */
    func Match(pattern:String) -> [String]
    {
        let nsstr = self as NSString
        var returns:[String] = []
        if let regex = try? NSRegularExpression(pattern:pattern, options:NSRegularExpressionOptions())
        {
            if let result = regex.firstMatchInString(nsstr as String, options: NSMatchingOptions(), range: NSMakeRange(0, nsstr.length))
            {
                for var i : Int = 0; i < result.numberOfRanges; ++i
                {
                    returns.append(nsstr.substringWithRange(result.rangeAtIndex(i)))
                }
            }
        }
        return returns
    }
    
    /**
    正規表現で検索を行う
    - parameter pattern:検索パターン
    - returns:[[String]]で検索結果を返す
    */
    func Matches(pattern:String) -> [[String]]
    {
        let nsstr = self as NSString
        var returns:[[String]] = []
        if let regex = try? NSRegularExpression(pattern:pattern,options:NSRegularExpressionOptions()){

            let result = regex.matchesInString(nsstr as String, options: NSMatchingOptions(), range: NSMakeRange(0, nsstr.length))
            for var i = 0; i < result.count; ++i
            {
                var temp : [String] = []
                for var j = 0; j < result[i].numberOfRanges; j++
                {
                    temp.append(nsstr.substringWithRange(result[i].rangeAtIndex(j)))
                }
                returns.append(temp)
            }
        
        }
        return returns
    }
13
16
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
13
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?