2012-01-21 43 views
0

給定一個字符串,像這樣:NSRegularExpression,字符串選擇部分

Seat 2: Pet21 ($1.98 in chips) 

在PHP中,您可以選擇使用括號在正則表達式正則表達式的一部分,就像這樣:

Seat ([0-9]+): (.{1,12}) .[$|€|£]([0-9]+\.?[0-9]{0,2}) in chips. 

這選擇座位號,用戶ID和籌碼數量:

Array 
(
    [0] => Array 
     (
      [0] => Seat 1: [email protected] ($0.83 in chips) 
      [1] => Seat 2: Pet21 ($1.98 in chips) 
      [2] => Seat 3: derphurp ($2.76 in chips) 
      [3] => Seat 4: -M-A-R-K-qaz ($0.92 in chips) 
      [4] => Seat 5: Rolle55 ($2.45 in chips) 
      [5] => Seat 6: SanderDecler ($2 in chips) 
     ) 

    [1] => Array 
     (
      [0] => 1 
      [1] => 2 
      [2] => 3 
      [3] => 4 
      [4] => 5 
      [5] => 6 
     ) 

    [2] => Array 
     (
      [0] => [email protected] 
      [1] => Pet21 
      [2] => derphurp 
      [3] => -M-A-R-K-qaz 
      [4] => Rolle55 
      [5] => SanderDecler 
     ) 

    [3] => Array 
     (
      [0] => 0.83 
      [1] => 1.98 
      [2] => 2.76 
      [3] => 0.92 
      [4] => 2.45 
      [5] => 2 
     ) 

) 

有沒有辦法做類似的objective-c wi日NSRegularExpression

編輯:到目前爲止,我有這樣的:

NSRegularExpression *regex = 
    [NSRegularExpression regularExpressionWithPattern:@"Seat [0-9]+: (.{1,12}) .[$|€|£][0-9]+\.?[0-9]{0,2} in chips." 
               options:0 
               error:nil]; 

    for (NSTextCheckingResult *result in [regex matchesInString:history options:NSMatchingReportCompletion range:NSMakeRange(0, history.length)]) 
    { 

    } 

回答

3

你可能想使用的NSRegularExpressionfirstMatchInString:options:range:方法,它返回一個NSTextCheckingResult。然後,您想使用NSTextCheckingResultrangeAtIndex:方法來獲取每個子匹配的範圍。您可以將範圍傳遞給原始NSStringsubstringWithRange:方法以獲取子匹配的文本。

+0

這樣做,非常感謝! –

+0

好的答案,小的補充:您需要在字符串中避免反斜槓,即'\ .'應該是'\\。'。 – omz