Saturday, November 13, 2010

sed for iphone

Here is a simple sed for iphone using RegexKitLite:

// input - input string
// search - regex to search
// replace - string to replace with
// return value - output string

const char* sed(const char* input, const char* search,const char* replace) {
static char buf[100000];   // assume the output string length <100000
NSString *searchString      = [NSString stringWithFormat:@"%s",input];
NSString *regexString       = [NSString stringWithFormat:@"%s",search];
NSString *replaceWithString = [NSString stringWithFormat:@"%s",replace];
NSString *replacedString    = NULL;
replacedString = [searchString stringByReplacingOccurrencesOfRegex:regexString withString:replaceWithString];
NSLog(@"replaced string: '%@'", replacedString);
strcpy(buf, [replacedString UTF8String]);
return buf;
}

sample usage:

char* buf = sed (str, "[ \\t]+", " "); // replace multiple white spaces with one space
                                               // note you need double \\

To use it, you need to 
1. download RegexKitLite
2. add RegexKitLite.h and RegexKitLite.m to your Xcode project
3. add libcucore.dylib to Frameworks of your Xcode project


Search the web for RegexKitLite:
For documentation of regex, see http://userguide.icu-project.org/strings/regexp

No comments:

Post a Comment