使用stringByReplacingOccurrencesOfString来考虑"单词"

时间:2014-10-15 03:44:31

标签: ios regex replace nsstring

我的目标是使用stringByReplacingOccurrencesOfString替换单词或短语的替换。单词及其替换词可以在字典中找到,例如单词或短语是键,它们的值是它们的替代词:

{"is fun" : "foo",
 "funny" : "bar"}

因为stringByReplacingOccurrencesOfString是字面意思并且忽略了西方语言惯例中的“单词”,所以我遇到了以下句子的麻烦:

  

“他很有趣 ny并且很有趣”,

实际上使用这种方法检测到“很有趣”这个短语两次:首先作为“很有趣”的一部分,第二部分作为“很有趣”的一部分,导致文字出现问题出现用于单词替换,并没有意识到它实际上是另一个单词的一部分。

我想知道是否有一种方法可以使用stringByReplacingOccurrencesOfString来考虑措辞,因此像“有趣”这样的短语可以在其完整的自我中查看,也不会被视为“< strong>很有趣 ny“where”很有趣“被检测到。

顺便说一句,这是我在迭代字典中的所有键时用来替换的代码:

NSString *newText = [wholeSentence stringByReplacingOccurrencesOfString:wordKey withString:wordValue options:NSLiteralSearch range:[wholeSentence rangeOfString:stringByReplacingOccurrencesOfString:wordKey]];
        iteratedTranslatedText = newText;

编辑1 :使用建议的解决方案,这就是我所做的:

NSString *string = @"Harry is fun. Shilp is his fun pet dog";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\bis fun\b" options:0 error:nil];
if (regex != nil) {
    NSTextCheckingResult *firstMatch = [regex firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];
    //firstMatch is returning null
    if (firstMatch) {
        NSRange resultRange = [firstMatch rangeAtIndex:0];
        NSLog(@"first match at index:%lu", (unsigned long)resultRange.location);

    }
}

但是,这会将firstMatch返回为null。根据关于单词边界的正则表达式tutorial,这是如何锚定单词或短语,所以我不确定为什么它不返回任何东西。感谢帮助!

1 个答案:

答案 0 :(得分:1)

作为评论,您可以在项目中使用NSRegrlarEXPression。例如:

NSString *string = @"He is funny and is fun";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"is fun([^a-zA-Z]+|$)" options:0 error:nil];
if (regex != nil) {
    NSTextCheckingResult *firstMatch = [regex firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];
    if (firstMatch) {
        NSRange resultRange = [firstMatch rangeAtIndex:0];
        NSLog(@"first match at index:%d", resultRange.location);
    }
}

结果:首先匹配指数:16

相关问题