1
votes

example: word with number in string

NSString *str = [NSString stringWithFormat:@"this is an 101 example1 string"]

Since example1 has a number in the end and i want to remove it. I can break it into an array and filter it out using predicate, but that seems slow to me since I need to do like a million of these.

What would be a more efficient way?

Thanks!

2

2 Answers

3
votes

Probably NSRegularExpression. I think ([^0-9 ]+)\d+|\d+([^0-9 ]+) should do it. Just replace it with $1.

2
votes

Based on Chuck's response, here is the complete code in case someone might find it useful:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([^0-9 ]+)\\d+|\\d+([^0-9 ]+)"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSString *modifiedString = [regex stringByReplacingMatchesInString:str2
                                                           options:0
                                                             range:NSMakeRange(0, [str2 length])
                                                      withTemplate:@"$1"];