-->

的NSMutableString修改而迭代文本检查结果(NSMutableString modify

2019-10-18 16: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.

Answer 1:

我找到了答案......我只是有点笨(不睡一会儿^^)。 迭代时按相反的顺序串,没关系的长度变化:

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


文章来源: NSMutableString modify while iterating text checking results