Pregunta

I am a beginner in objective-c.

I have the following NSMutableString stringVal=@"[abc][test][end]";

What is the best way I should use in order to REMOVE THE LAST [] piece (e.g [end])?

I have this code:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\[]" options:0 error:NULL];
    NSArray *matches = [regex matchesInString:stringVal options:0 range:NSMakeRange(0, [stringVal length])];
    for (NSTextCheckingResult *match in matches) {
        ?? what should i do here?
    }
¿Fue útil?

Solución

I think you should use this regular expression pattern "\\[.*?]" then you get three matches

['[abc]', '[test]', '[end]']

then can just get the range of the third match (check that you have at least three)

NSMutableString* stringVal= [NSMutableString stringWithString:@"[abc][test][end]"];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[.*?]" options:0 error:NULL];
NSArray *matches = [regex matchesInString:stringVal options:0 range:NSMakeRange(0, [stringVal length])];
NSTextCheckingResult* match = matches[2];

NSMutableString* substring = [[stringVal substringToIndex:match.range.location] mutableCopy];

Otros consejos

jbat was right that you should modify the regex. After that, all you need is the last match, so you could use

NSTextCheckingResult *match = [matches lastObject]; // Get the last match
NSRange matchRange = [match range]; // Get the position of the match segment
NSString *result = [stringVal stringByReplacingCharactersInRange:matchRange  withString:@""]; // Replace the segment by an empty string.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top