2

I'd like to use enumerateMatchInString to find every abbreviation a call my method ConvertAbbreviation:(NSString *)abbr; to covert that abbreviation and return the full string.

Can someone help me with this? I am getting exceptions when I try the code below. If this is wrong can someone please give me an example of how to modify the original text within the block.

- (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;
}
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Faz Ya
  • 1,480
  • 2
  • 15
  • 22
  • 1
    You probably don't want to match the trailing whitespace. Use a positive lookahead: `[a-zA-Z.]+\\.(?=\\s|\\n|$)`. It will match it but not inlude it in the actual match result. – Regexident Jul 10 '12 at 12:33

2 Answers2

14

You should try a backwards search, otherwise once you modify the text the first time your text ranges are no longer valid.

So, enumerate over all matches like this (you can use this trick to go backwards):

NSArray *results = [matchAnyPotentialAbv matchesInString:textBlock options:kNilOptions range:NSMakeRange(0, textBlock.length)];

for(NSTextCheckingResult *result in [results reverseObjectEnumerator])
{
    //Replace
}
borrrden
  • 33,256
  • 8
  • 74
  • 109
2

Using NSRegularExpression's -replacementStringForResult:inString:offset:template:] API probably provides a cleaner way to do this, and worked well for me. For a usage guide, see:

How do you use NSRegularExpression's replacementStringForResult:inString:offset:template:

Community
  • 1
  • 1
Stuart M
  • 11,458
  • 6
  • 45
  • 59