NSMutableString modify while iterating text checki

2019-08-10 19:52发布

问题:

I'm trying to modify an NSString while iterating NSTextCheckingResults from an NSRegularExpression.

I know that it won't work the way I implemented it as every replacement changes the length of the string an so the validity of the NSRages in my loop.

How can I replace multiple matches in a for loop? Here is my code:

NSMutableString *string = [@"[H]…[mm]…[s]" mutableCopy];
NSReguralExpression *exp = [NSRegularExpression regularExpressionWithPattern:@"(\\[[Hms]{1,2}\\])" options:0 error:nil];

for (NSTextCheckingResult *result in [exp matchesInString:string options:NSMatchingReportCompletion range:NSMakeRange(0, [string length])]) {
    [string replaceCharactersInRange:[result rangeAtIndex:0] withString:@"#"];
}

I'm a bit stuck right now. None of the approaches I thought of seemed to be functional.

回答1:

I found the answer… I was just a bit stupid (didn't sleep for a while ^^). When iterating a string in reverse order, it does not matter that the length changes:

for (NSTextCheckingResult *result in [[exp matchesInString:string optinos:NSMatchingReportCompletion range:NSMakeRange(0, [string length])] reverseObjectEnumerator]) {
    // …
}