NSMutableString modify while iterating text checki

2019-08-10 19:29发布

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条回答
Luminary・发光体
2楼-- · 2019-08-10 20:06

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]) {
    // …
}
查看更多
登录 后发表回答