2012-03-07 39 views
2

我想用NSRegularExpression提取字符串的部分。使用NSRegularExpression從正則表達式提取零件

例如,我有這個字符串:

@"1 UIKit        0x00540c89 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1163"; 

而且我想提取 「的UIKit」, 「0x00540c89」, 「UIApplication的」, 「_callInitializationDelegatesForURL:有效載荷:暫停」 和 「1163」。

我已經maked正則表達式:

@"^[0-9]+\\s+[a-zA-Z]+\\s+0x[0-9a-zA-Z]+\\s+\\-\\s*\\[[a-zA-Z]+\\s+[_:a-zA-Z]+\\]\\s+\\+\\s+[0-9]+" 

但我不知道我怎麼也得這樣做。有可能的。

NSString *origen = @"1 UIKit        0x00540c89 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1163"; 
    // Setup an NSError object to catch any failures 
    NSError *error = NULL; 
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]+\\s+[a-zA-Z]+\\s+0x[0-9a-zA-Z]+\\s+\\-\\s*\\[[a-zA-Z]+\\s+[_:a-zA-Z]+\\]\\s+\\+\\s+[0-9]+" 
                      options:NSRegularExpressionCaseInsensitive 
                      error:&error]; 
    // create an NSRange object using our regex object for the first match in the string 
    NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:origen options:0 range:NSMakeRange(0, [origen length])]; 
    // check that our NSRange object is not equal to range of NSNotFound 
    if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) { 
     // Since we know that we found a match, get the substring from the parent string by using our NSRange object 
     NSString *substringForFirstMatch = [origen substringWithRange:rangeOfFirstMatch]; 
     NSLog(@"Extracted: %@",substringForFirstMatch); 
    } 

回答

3

試試這個:

NSCharacterSet *separatorSet = [NSCharacterSet characterSetWithCharactersInString:@" -[]+?.,"]; 
NSMutableArray *array = [origen componentsSeparatedByCharactersInSet:separatorSet]; 
[array removeObject:@""]; 
3

你顯然需要一種方法,以配合您的正則表達式多個範圍。這是通過用圓括號表示的匹配組完成的。然後,您可以使用NSRegularExpression方法中的一個,該方法將爲您提供NSTextCheckingResult而不是簡單的範圍。 NSTextCheckingResult可以包含多個範圍。

實施例:

NSString *pattern = @"^[0-9]+\\s+([a-zA-Z]+)\\s+(0x[0-9a-zA-Z]+)\\s+\\-\\s*(\\[[a-zA-Z]+\\s+[_:a-zA-Z]+\\])\\s+\\+\\s+([0-9]+)"; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern 
                     options:NSRegularExpressionCaseInsensitive 
                     error:&error]; 

NSTextCheckingResult *firstResult = [regex firstMatchInString:origen options:0 range:NSMakeRange(0, origen.length)]; 
if ([firstResult numberOfRanges] == 5) { 
    //The range at index 0 contains the entire string. 
    NSLog(@"1: '%@'", [origen substringWithRange:[firstResult rangeAtIndex:1]]); 
    NSLog(@"2: '%@'", [origen substringWithRange:[firstResult rangeAtIndex:2]]); 
    NSLog(@"3: '%@'", [origen substringWithRange:[firstResult rangeAtIndex:3]]); 
    NSLog(@"4: '%@'", [origen substringWithRange:[firstResult rangeAtIndex:4]]); 
}