NSMutableString modify while iterating text checking results

本秂侑毒 提交于 2019-12-11 09:01:06

问题


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]) {
    // …
}


来源:https://stackoverflow.com/questions/18919934/nsmutablestring-modify-while-iterating-text-checking-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!