Ios stringbyreplacing字符串替换较长单词组合的出现

Ios stringbyreplacing字符串替换较长单词组合的出现,ios,objective-c,regex,string,nsstring,Ios,Objective C,Regex,String,Nsstring,当使用stringByReplacingOccurrencesOfString时,它似乎会替换单词中的单词。那么比如说, The house was held together by... 将出现的“the”替换为“A”将导致 A house was held togeAr by... 我怎样才能避免这种情况?我知道我可以在被替换的单词的任意一侧添加空格,以确保它不是较长单词的一部分,但是这并不适用于所有情况,特别是在被替换的单词是句子中的第一个或最后一个单词的情况下(即,当两边都没有空格时

当使用
stringByReplacingOccurrencesOfString
时,它似乎会替换单词中的单词。那么比如说,

The house was held together by...
将出现的“the”替换为“A”将导致

A house was held togeAr by...

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

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

有关更复杂的替换操作,可以使用
NSRegularExpression
。您可以搜索类似($)的内容并替换匹配项。

您应该使用带有模式
\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...

您应该将
NSRegularExpression
与模式
\b
一起使用,其中
\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...

哇,真是太感谢你了。这么简单。以前从未听说过正则表达式。嗯,听说过他们,不知道他们是什么。这解决了一个我一直坚持的问题。我有各种各样的精心制作的技巧来尝试让它发挥作用……哇,我真的太感谢你了。这么简单。以前从未听说过正则表达式。嗯,听说过他们,不知道他们是什么。这解决了一个我一直坚持的问题。我有各种各样复杂的技术来尝试让它工作。。。