2016-07-12 5 views
-2

正規表現パターンと一致する文字列から部分文字列を抽出します。swift正規表現と(。*?)

問題はこのコードです:("ytplayer.config = {(.*?)};").exec(responseStringC)。一致する必要がありますが、nilを返します。

string.exec機能:

extension String { 
    func exec (str: String) -> Array<String> { 
     do { 
      let regex = try NSRegularExpression(pattern: self, options: [.CaseInsensitive,.IgnoreMetacharacters]) 
      let nsstr = str as NSString 
      let all = NSRange(location: 0, length: nsstr.length) 
      var matches : Array<String> = Array<String>() 
      regex.enumerateMatchesInString(str, options: NSMatchingOptions(rawValue: 0), range: all) { 
       (result : NSTextCheckingResult?, _, _) in 
       let theResult = nsstr.substringWithRange(result!.range) 
       matches.append(theResult) 
      } 
      return matches 
     } catch { 
      print("error") 
      return Array<String>() 
     } 
    } 
} 

"responseStringC" 変数は次のとおりです。

http://pastebin.com/uvvq9ULA

問題がnilを返すです。どんな手掛かり?

+3

を参照してください。 。 – matt

+0

あなたの問題は何ですか?コンパイル中やアプリの実行中にエラーがありますか? – FelixSFD

+0

リターンnil。合わない。 –

答えて

1

あなたexecコードが.IgnoreMetacharacters flag含まれています

は、文字列リテラルとしてパターン全体を扱います。

パターンを削除して、正規表現パターンとして扱うことができます。

また、パターンの先頭にDOTALL修飾子(?s)を使用することをお勧めします。

また、ドットは任意の文字に一致し、リテラルドットと一致するようにエスケープすることに注意してください。

パターンとして、私は

"(?s)ytplayer\\.config = \\{(.*?)\\};" 

または、はるかに高速をお勧めします:

"(?s)ytplayer\\.config = \\{([^}]*(?:\\}(?!;)[^}]*)*)\\};" 

は私も質問はここにあるかを把握することはできませんregex demo

+0

' "(?s )ytplayer \\。config = \\ {(。*?)\\}; "'。ありがとう –

+0

はい、ごめんなさい、エスケープを忘れました。更新しました。 –