我想使用enumerateMatchInString
查找每个缩写a
调用我的方法ConvertAbbreviation:(NSString *)abbr;
来隐藏该缩写并返回完整的字符串。
有人可以帮我吗?我在尝试下面的代码时遇到异常。 如果这是错的,有人可以给我一个如何修改块内原始文本的例子。
- (NSString *) convertAllAbbreviationsToFullWords:(NSString *) textBlock {
NSRegularExpression *matchAnyPotentialAbv = [NSRegularExpression regularExpressionWithPattern:@"[a-zA-Z\\.]+\\.\\s" options:0 error:nil];
[matchAnyPotentialAbv
enumerateMatchesInString:textBlock
options:0
range:NSMakeRange(0, [textBlock length])
usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
/* on each match, I would like to call convert(match) and
replace the result with the existing match in my textBlock */
if (++count >= 200) *stop = YES;
}
];
return textBlock;
}
答案 0 :(得分:11)
您应该尝试向后搜索,否则在第一次文本范围不再有效时修改文本。
所以,列举所有这样的匹配(你可以使用这个技巧倒退):
NSArray *results = [matchAnyPotentialAbv matchesInString:textBlock options:kNilOptions range:NSMakeRange(0, textBlock.length)];
for(NSTextCheckingResult *result in [results reverseObjectEnumerator])
{
//Replace
}
答案 1 :(得分:2)
使用NSRegularExpression的-replacementStringForResult:inString:offset:template:]
API可能提供了一种更简洁的方法,并且对我来说效果很好。有关使用指南,请参阅:
How do you use NSRegularExpression's replacementStringForResult:inString:offset:template: