2016-04-29 22 views
1

こんにちは私は()の間にテキストを抽出したいと思います。例えば括弧内の単語を抽出するSwift正規表現

(some text) some other text -> some text 
(some) some other text  -> some 
(12345) some other text -> 12345 

括弧の間の文字列の最大長は10個の文字であるべきです。うまく動作

let regex = try! NSRegularExpression(pattern: "\\(\\w+\\)", options: []) 

regex.enumerateMatchesInString(text, options: [], range: NSMakeRange(0, (text as NSString).length)) 
{ 
    (result, _, _) in 
     let match = (text as NSString).substringWithRange(result!.range) 

     if (match.characters.count <= 10) 
     { 
      print(match) 
     } 
} 

しかし試合は、次のとおりです:

(TooLongStri) -> nothing matched because 11 characters 

は、私が現在持っていることである

(some text) some other text -> (some text) 
(some) some other text  -> (some) 
(12345) some other text -> (12345) 

と()もカウントされるため、< = 10と一致していません。

私はそれを解決するために上記のコードをどのように変更できますか?また、長さ情報を保持する正規表現を拡張してif (match.characters.count <= 10)を削除したいと思います。

答えて

3

あなたは​​

パターンを参照してください

"(?<=\\()[^()]{1,10}(?=\\))" 

使用することができます。

  • (?<=\\()を - 現在のポジ前(の存在を主張しますあればチェック - どれも
  • [^()]{1,10}が存在しない場合ションとは一致して失敗した -
  • (?=\\))()以外の1〜10文字にマッチします(英数字のみ/アンダー文字を一致させる必要がある場合\w[^()]を置き換えます)現在の位置の後ろに)の文字列を置き、存在しない場合は一致しません。

あなたが単純な正規表現を使用することができます範囲1(キャプチャグループ)の値を得るためにあなたのコードを調整することができた場合:

"\\(([^()]{1,10})\\)" 

regex demoを参照してください。必要な値はキャプチャグループ1内です。

2

これは、これも動作します

\((?=.{0,10}\)).+?\) 

Regex Demo

動作します

\((?=.{0,10}\))([^)]+)\) 

Regex Demo

正規表現内訳

\(#Match the bracket literally 
(?=.{0,10}\)) #Lookahead to check there are between 0 to 10 characters till we encounter another) 
([^)]+) #Match anything except) 
\) #Match) literally 
関連する問題