views:

31

answers:

0

I have a C# project I'm intending to port to Objective-C. From http://stackoverflow.com/questions/422138/regular-expressions-in-an-objective-c-cocoa-application, it looks like there's a confusing variety of Regex options but I can't see anything about a way of doing a replace with callback. That is, the equivalent of the C# MatchEvaluator delegate or PHP's preg_replace_callback. An example of what I want to do in C# is -

// change input so each word is followed a number showing how many letters it has
string inputString = "Hello, how are you today ?";
Regex theRegex = new Regex(@"\w+");
string outputString = theRegex.Replace(inputString, delegate (Match thisMatch){
   return thisMatch.Value + thisMatch.Value.Length;
});
// outputString is now 'Hello5, how3 are3 you3 today5 ?'

How could I do this in Objective-C ? If not directly possible, any alternatives would be great. In my actual situation the Regex has both lookahead and lookbehind assertions in it though, so any alternative involving finding the strings in advance and then doing a series of straight string replaces won't work unfortunately.