【问题标题】:stringByReplacingOccurrencesOfString replacing composites of longer wordsstringByReplacingOccurrencesOfString 替换较长单词的组合
【发布时间】:2012-05-24 13:34:21
【问题描述】:

当使用stringByReplacingOccurrencesOfString 时,它似乎会替换单词中的单词。例如,

The house was held together by...

将出现的“the”替换为“A”将导致

A house was held togeAr by...

我怎样才能避免这种情况?我知道我可以在被替换的单词的任一侧添加空格以确保它不是更长单词的一部分,但这并不适用于所有情况,特别是在被替换的单词是句子中的第一个或最后一个单词的情况下(也就是说,当两边都没有空白时)。

【问题讨论】:

    标签: ios objective-c regex string nsstring


    【解决方案1】:

    您应该使用带有\bthe\b 模式的NSRegularExpression,其中\b 表示单词边界。

    NSString *input = @"The house was held together by...";
    NSString *string = @"the";
    NSString *replacement = @"A";
    
    NSString *pattern = [NSString stringWithFormat:@"\\b%@\\b", string];
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *result = [regex stringByReplacingMatchesInString:input options:0 range:NSMakeRange(0, input.length) withTemplate:replacement];
    
    NSLog(@"%@", result);
    // A house was held together by...
    

    【讨论】:

    • 哇,真是太感谢你了。很简单。以前从未听说过正则表达式。好吧,听说过他们,不知道他们是什么。这解决了我困扰了一段时间的问题。我有各种精心设计的技术来尝试让它发挥作用......
    【解决方案2】:

    对于更复杂的替换操作,可以使用NSRegularExpression。您可以搜索 (^| )the($| ) 之类的内容并替换匹配项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多