Gianluca
Gianluca

Reputation: 2449

regex to extract all the substrings between two characters or tags

I need to extract all the strings surrounded by two characters (or maybe two tags)

this is what I've done so far:

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]" options:NSRegularExpressionCaseInsensitive error:NULL];

    NSArray *myArray = [regex matchesInString:@"[db1]+[db2]+[db3]" options:0 range:NSMakeRange(0, [@"[db1]+[db2]+[db3]" length])] ;

    NSLog(@"%@",[myArray objectAtIndex:0]);
    NSLog(@"%@",[myArray objectAtIndex:1]);
    NSLog(@"%@",[myArray objectAtIndex:2]);

In myArray there are correctly three objects but NSlog prints this:

<NSSimpleRegularExpressionCheckingResult: 0x926ec30>{0, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1}
<NSSimpleRegularExpressionCheckingResult: 0x926eb30>{6, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1}
<NSSimpleRegularExpressionCheckingResult: 0x926eb50>{12, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1}

instead of db1, db2 and db3

where I'm wrong?

Upvotes: 7

Views: 7765

Answers (2)

Damien Romito
Damien Romito

Reputation: 10055

Or this

NSArray *results = [@"[db1]+[db2]+[db3]" matchWithRegex:@"\\[(.*?)\\]"];

//result = @["db1","db2,"db3"]

With this category https://github.com/damienromito/NSString-Matcher

Upvotes: 0

Joe
Joe

Reputation: 57169

According to the documentation matchesInString:options:range: returns an array of NSTextCheckingResults not NSStrings. You will need to loop over the results and use the ranges to get the substrings.

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]" options:NSRegularExpressionCaseInsensitive error:NULL];

NSString *input = @"[db1]+[db2]+[db3]";
NSArray *myArray = [regex matchesInString:input options:0 range:NSMakeRange(0, [input length])] ;

NSMutableArray *matches = [NSMutableArray arrayWithCapacity:[myArray count]];

for (NSTextCheckingResult *match in myArray) {
     NSRange matchRange = [match rangeAtIndex:1];
     [matches addObject:[input substringWithRange:matchRange]];
     NSLog(@"%@", [matches lastObject]);
}

Upvotes: 20

Related Questions