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?
NSRegularExpressionis available only since iOS 4.0 and the string should have predictable regex for this to work as one would guess.The above code works. You will have to see if it fits your HTML use case.
Getting the ages
You will use the
enumerateMatchesInString:options:range:usingBlock:method to enumerate through all the matches. You will get aNSTextCheckingResultobject 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,