Search code examples
iosobjective-cregexnsregularexpression

iOS Split NSString with Regular Expression


I am using this code to parse NSString:

    NSString *string = @"{{nat fs g player|no=1|pos=GK|name=[[Hugo Lloris]]|age={{Birth date and age|1986|12|26|df=y}}|caps=73|goals=0|club=[[Tottenham Hotspur F.C.|Tottenham Hotspur]]|clubnat=ENG}}";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{nat fs g player\\|no=(.*)\\|pos=(.*?)\\|name=\\[\\[(.*?)\\]\\]\\|age=\\{\\{Birth date and age\\|(.*?)\\|(.*?)\\|(.*?)\\|df=y\\}\\}\\|caps=(.*?)\\|goals=(.*?)\\|club=\\[\\[(.*?)\\|(.*)"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSArray *matches = [regex matchesInString:string
                                  options:0
                                    range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
    NSString *a = [string substringWithRange:[match rangeAtIndex:0]];
    NSString *b = [string substringWithRange:[match rangeAtIndex:1]];
    NSString *c = [string substringWithRange:[match rangeAtIndex:2]];
    NSString *d = [string substringWithRange:[match rangeAtIndex:3]];
    NSString *e = [string substringWithRange:[match rangeAtIndex:4]];
    NSString *f = [string substringWithRange:[match rangeAtIndex:5]];
    NSString *g = [string substringWithRange:[match rangeAtIndex:6]];
    NSString *h = [string substringWithRange:[match rangeAtIndex:7]];
    NSString *i = [string substringWithRange:[match rangeAtIndex:8]];
    NSString *j = [string substringWithRange:[match rangeAtIndex:9]];
    NSString *k = [string substringWithRange:[match rangeAtIndex:10]];
}

With this code i really get the data, but when i am trying to split 2 strings with the same pattern:

NSString *string = @"{{nat fs g player|no=1|pos=GK|name=[[Hugo Lloris]]|age={{Birth date and age|1986|12|26|df=y}}|caps=73|goals=0|club=[[Tottenham Hotspur F.C.|Tottenham Hotspur]]|clubnat=ENG}}{{nat fs g player|no=16|pos=GK|name=[[Steve Mandanda]]|age={{Birth date and age|1985|3|28|df=y}}|caps=21|goals=0|club=[[Olympique de Marseille|Marseille]]|clubnat=FRA}}";

I am getting only one match,any idea why?


Solution

  • You need to fix your regex to allow partial matches.

    Since the record ends with }}, use lazy (.*?\}\}) in the last capturing group.

    The regex declaration will be:

    NSString *pattern = @"\\{\\{nat fs g player\\|no=([^|]*)\\|pos=([^|]*)\\|name=\\[\\[([^|]*)\\]\\]\\|age=\\{\\{Birth date and age\\|([^|]*)\\|([^|]*)\\|([^|]*)\\|df=y\\}\\}\\|caps=([^|]*)\\|goals=([^|]*)\\|club=\\[\\[([^|]*)\\|(.*?\\}\\})";
    

    See IDEONE demo