【发布时间】:2014-02-04 02:35:44
【问题描述】:
我已经尝试了几个小时,但在互联网上找不到类似的东西,所以希望你能帮助我..
我正在尝试替换 NSString 中的单个字符,应该很简单吧? 这是我所做的:
NSError *error;
NSString *str1 = @"E bis the EVE E on E is the the hte ee e.";
NSString *str2 = @"E abis the EVE E on E is the the hte ee e.";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\bE\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
int numberOfMatches1 = [regex numberOfMatchesInString:str1
options:0
range:NSMakeRange(0, [str1 length])];
int numberOfMatches2 = [regex numberOfMatchesInString:str2
options:0
range:NSMakeRange(0, [str2 length])];
NSLog(@"%d, %d",numberOfMatches1,numberOfMatches2);
NSString *modifiedStr1 = [regex stringByReplacingMatchesInString:str1
options:0
range:NSMakeRange(0, [str1 length])
withTemplate:@"O"];
NSString *modifiedStr2 = [regex stringByReplacingMatchesInString:str2
options:0
range:NSMakeRange(0, [str2 length])
withTemplate:@"O"];
NSLog(modifiedStr1);
NSLog(modifiedStr2);
我们的想法是用 O 替换所有单个 E(也位于字符串的开头和结尾),并保留所有其他 E。 在第一个字符串中,这按预期工作,但是当我在字符串中添加一些东西时,在这种情况下,第二个位置的“a”会出现误报。 输出是:
4, 5 (str1 和 str2 匹配的 Nr)
O bis the EVE O on O 是hte ee O。
O abis the EVE O on O is the thO hte ee O.
我做错了什么?
【问题讨论】:
标签: objective-c regex nsregularexpression