2012-03-07 2 views
2

NSRegularExpression을 사용하여 문자열의 일부를 추출하고 싶습니다.NSRegularExpression을 사용하여 정규 표현식을 추출합니다.

예를 들어,이 문자열이 있습니다

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

을 그리고 "UIKit", "0x00540c89", "UIApplication", 추출 싶다 "_callInitializationDelegatesForURL : 중지 : 페이로드"와 "1163".

나는 정규 표현식을 표시했습니다했다 :

@"^[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]]); 
} 
관련 문제