0

I have a string, dynamically generated from a website, that I would like to change.

I already know you need to change the string to a NSMutableString, but the part I want to remove is almost never the same. (e.g. [XXXXX] or [XABXX] ... there are thousands of combos).

The only static parts are the square brackets on either end and that there are 5 characters in between.

How would I recognise and remove this string of seven characters ([*****], with the *'s representing a random letter)?

1
  • maybe with regular expression...? Commented Sep 15, 2013 at 16:57

2 Answers 2

3

A simple search and you can find it here:

with a simple change:

- (NSString *)stringCleaner:(NSString *)yourString {
    NSScanner *theScanner;
    NSString *text = nil;

    theScanner = [NSScanner scannerWithString:yourString];

    while ([theScanner isAtEnd] == NO) {
        [theScanner scanUpToString:@"[" intoString:NULL] ;
        [theScanner scanUpToString:@"]" intoString:&text] ;
        yourString = [yourString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@]", text] withString:@""];
    }

    return yourString;
}
Sign up to request clarification or add additional context in comments.

2 Comments

can you put this in an IBAction?
sure, you can set a IBAction method with that code but instead of returning the string will just set the value where you need it or just do this: //add this action to UIButton - (IBAction)buttonAction:(id)sender { NSString *finalString = [self stringCleaner:@"mytext[azert]toReplace"]; //do something with finalString }
1

Look at using the NSRegularExpression class to find each substring you need to operate on.

4 Comments

I was able to get it to work with regexes, except for NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\[" (... replace with "") If I do this, I get a blank output. Any other regex is fine. Is there a way that you know works to remove a "["?
\[ is the correct escape sequence. Did you use \[\d{5}\] ?
I get unknown escape sequence for \d and \]
nevermind. Just note that in obj-c, you need to escape like this: \\[

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.