2012-01-21 44 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