Reputation: 329
How do I search through a string for a particular substring and find the positions of each matching item.
For example,
NSString *theText = @"name - dave, age - 30, favNum - 7, name - peter, age - 8, favNum - 10";
In this example, I am trying to find all the ages and replace them with 50. What is the best way of doing so?
Upvotes: 0
Views: 1470
Reputation: 44633
NSRegularExpression
is available only since iOS 4.0 and the string should have predictable regex for this to work as one would guess.
NSString *theText = @"name - dave, age - 30, favNum - 7, name - peter, age - 8, favNum - 10";
NSRegularExpression * regularExpression = [NSRegularExpression regularExpressionWithPattern:@"(?<= age - )\\d+"
options:0
error:nil];
NSString * alteredText = [regularExpression stringByReplacingMatchesInString:theText
options:0
range:NSMakeRange(0, [theText length])
withTemplate:@"50"];
NSLog(@"%@", alteredText);
The above code works. You will have to see if it fits your HTML use case.
You will use the enumerateMatchesInString:options:range:usingBlock:
method to enumerate through all the matches. You will get a NSTextCheckingResult
object for each iteration which will hold the range information about the match. So you will need to do this before you replace the string. You can get the ages in an array doing,
NSMutableArray * ages = [NSMutableArray array];
[regularExpression enumerateMatchesInString:theText
options:0
range:NSMakeRange(0, [theText length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop){
[ages addObject:[NSNumber numberWithInt:[[theText substringWithRange:result.range] intValue]]];
}];
NSLog(@"%@", ages);
Upvotes: 2
Reputation: 17170
You will have to disassemble the string and then rebuild it. It is not possible to replace characters in an NSString.
First you need to split the string into components. Use NSString's -(NSArray*)componentsSeperatedByString(@"age")
or maybe -(NSArray*)componentsSeperatedByString(@",")
to plit out your records. But then getting the digits needs more work. Use NSScanner.
You create an NSScanner with the string you want to scan: + (id)scannerWithString:(NSString *)aString
. So you would loop through the array returned above and scan a string then an integer.
To can over the strings, you need to use - (BOOL)scanCharactersFromSet:(NSCharacterSet )scanSet intoString:(NSString *)stringValue using the character set: [[NSCharacterSet decimalDigitCharacterSet] inverseCharacterSet] - this is the charachter set including all characters other than the digits. Note that scanCharacters from range gives you back the characters it scans and so you can use this to rebuild the string.
Then you could scan a integer using NSScanner's - (BOOL)scanInt:(int *)intValue
You could probably achieve something similar using NSPredicate and regexps - there would be less code but it would be less readable.
Upvotes: 0