David Karlsson
David Karlsson

Reputation: 9686

Objective-C regex to remove part of string

Hi im trying to remove som HTML string from a web response. I want to remove <pre><a style="" name="output-line-1">1</a>, were the who instances of number "1"varies, but is always a digit. but how do i write the regex method for removing this? Below is what i have got so far:

-(NSString *)stringByStrippingHTML:(NSString*)str
{
    NSRange r;
   while ((r = [str rangeOfString:@"/^<pre><a style=\"\"name=\"output-line-([0-9])\">([0-9])</a>"  options:NSRegularExpressionSearch]).location != NSNotFound){

        str = [str stringByReplacingCharactersInRange:r withString:@""];

    }
 }

Basically I want to remove a substring with random number in it... In some instances of the substring the 1 is replaced, so that any similar string gets acknowledged, for example it could be output-line-999. How do i combine the range of string so i can both describe the string and specify to find any similar string with any number?

I want to remove both the HTML and the numbers.

Upvotes: 0

Views: 1021

Answers (2)

Antonio MG
Antonio MG

Reputation: 20410

This regular expression should work:

[str rangeOfString:@"<pre><a style=\"\" name=\"output-line-[0-9]+\">[0-9]+</a>"  options:NSRegularExpressionSearch];

I thnk the problem is that there ins't a space before name in your reg expression

Upvotes: 1

Rob
Rob

Reputation: 437432

Using your original while loop, you can:

-(NSString *)stringByStrippingHTML:(NSString*)str
{
    NSRange r;
    while ((r = [str rangeOfString:@"<pre><a style=\"\" name=\"output-line-[0-9]+\">[0-9]+</a>"  options:NSRegularExpressionSearch]).location != NSNotFound) 
    {
        str = [str stringByReplacingCharactersInRange:r withString:@""];
    }
 }

Or you can use NSRegularExpression:

NSMutableString *input = ...

NSError *error;
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"<pre><a style=\"\" name=\"output-line-[0-9]+\">[0-9]+</a>"
                                                  options:0
                                                    error:&error];
if (error)
{
    NSLog(@"error=%@",error);
    return;
}

[regex replaceMatchesInString:input
                      options:0
                        range:NSMakeRange(0, [input length])
                 withTemplate:@""];

Upvotes: 0

Related Questions