Search code examples
iosobjective-cstaticsymbolsnsscanner

I want to remove static text from string - iOS


Hi I have a News Reader and I keep getting a string like this -

two New York police officers shot dead in 'ambush'

I want the string two New York police officers shot dead in ambush

How can I scan from & to ; and then delete occurrences of the scan.

I created a scanner like so -

NSString *webString222222 = filteredTitle2;
        NSScanner *stringScanner222222 = [NSScanner scannerWithString:webString222222];
        NSString *content222222 = [[NSString alloc] init];
        [stringScanner222222 scanUpToString:@"&" intoString:Nil];
        [stringScanner222222 scanUpToString:@";" intoString:&content222222];
        NSString *filteredTitle222 = [content222222 stringByReplacingOccurrencesOfString:content222222 withString:@""];
        NSString *filteredTitle22 = [filteredTitle222 stringByReplacingOccurrencesOfString:@"&" withString:@""];

But when I do this code the whole text disappears! Every single word. When I check the title in my NSLog that is the only & sign in there and the only ; sign in there! Im not sure where I went wrong here.


Solution

  • You can use NSRegularExpression to build proper matching pattern:

    NSString *pattern = @"\\&#[0-9]+;";
    NSString *str = @"two New York police officers shot dead in 'ambush'";
    
    NSLog(@"Original test: %@",str);
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:pattern
                                  options:NSRegularExpressionCaseInsensitive error:&error];
    if (error != nil)
    {
        NSLog(@"ERror: %@",error);
    } 
    else 
    {
        NSString *replaced = [regex stringByReplacingMatchesInString:str
                                                             options:0
                                                               range:NSMakeRange(0, [str length])
                                                        withTemplate:@""];
    
        NSLog(@"Replaced test: %@",replaced);
    }
    

    See https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSRegularExpression_Class/index.html