views:

2609

answers:

4

According to this guide, I can use NSPredicate to do regex matching on strings, i.e., the perl equivalent of $my_string =~ m/[some regex]/

But can I do regex replace, i.e. the equivalent of this perl expression: $my_string =~ s/[pattern]/[replacement]/g ?

+2  A: 

This functionality is not available natively in Cocoa, but you can use the standard c regex.h functions as described here (about three quarters of the way down the page).

There is also an open source library called ObjPCRE which may do the trick.

And someone was able to make it work using JavascriptCore.

Good luck!

e.James
+6  A: 

Google Toolbox for Mac has some useful regex functionality. It works on the iPhone. Take a look at GTMRegex.h. There is a category on NSString with this method:

- (NSString *)gtm_stringByReplacingMatchesOfPattern:(NSString *)pattern withReplacement:(NSString *)replacementPattern;
Chris Lundie
+5  A: 

The easiest solution I've found is RegexKitLite:

http://regexkit.sourceforge.net/

(Note the "Lite" version is the one you use for the iPhone)

Just two files to add to a project, and a -licucore flag for the linker. It uses the built in regex abilities.

It has NSString extensions, including ones to do replacements and can also pull out multiple matches by number.

Kendall Helmstetter Gelner
+1  A: 

In NSString.h, you'll find:

NSRegularExpressionSearch = 1024 /* Applies to rangeOfString:...,
                                    stringByReplacingOccurrencesOfString:...,
                                    and replaceOccurrencesOfString:... methods
                                    only; the search string is treated as an ICU-
                                    compatible regular expression; if set, no
                                    other options can apply except
                                    NSCaseInsensitiveSearch and
                                    NSAnchoredSearch */

Unless you need advanced regex features, this would suit you just fine in most cases.

Yon
Note: Only on iPhone, not Mac OS X (as of Mac OS X 10.6.3).
Peter Hosey