代码之家  ›  专栏  ›  技术社区  ›  Julian F. Weinert

NSMutableString在迭代文本检查结果时进行修改

  •  1
  • Julian F. Weinert  · 技术社区  · 11 年前

    我正在尝试修改 NSString 在迭代时 NSTextCheckingResults 来自 NSRegularExpression .

    我知道它不会像我实现的那样工作,因为每次替换都会改变字符串的长度,从而改变循环中NSRage的有效性。

    如何在for循环中替换多个匹配项?这是我的代码:

    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:@"#"];
    }
    

    我现在有点困。我想到的所有方法似乎都不起作用。

    1 回复  |  直到 11 年前
        1
  •  1
  •   Julian F. Weinert    11 年前

    我找到了答案——我只是有点傻(有一段时间没睡觉^^)。 以相反的顺序迭代字符串时,长度的变化并不重要:

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