Regular expressions in an Objective-C Cocoa application

Initial Googling indicates that there's no built-in way to do regular expressions in an Objective-C Cocoa application.

So four questions:

  1. Is that really true?

  2. Are you kidding me?

  3. Ok, then is there a nice open-source library you recommend?

  4. What are ways to get close enough without importing a library, perhaps with the NSScanner class?


I noticed that as of iOS 4.0 Apple provides a NSRegularExpression class. Additionally, as of 10.7, the class is available under OS X.


  1. Yes, there's no regex support in Cocoa. If you're only interested in boolean matching, you can use NSPredicate which supports ICU regex syntax. But usually you're interested in the position of the match or position of subexpressions, and you cannot get it with NSPredicate.
  2. As mentioned you can use regex POSIX functions. But they are considered slow, and the regex syntax is limited compared to other solutions (ICU/pcre).
  3. There are many OSS libraries, CocoaDev has an extensive list.
  4. RegExKitLite for example doesn't requires any libraries, just add the .m and .h to your project.

    (My complaint against RegExKitLite is that it extends NSString via category, but it can be considered as a feature too. Also it uses the nonpublic ICU libraries shipped with the OS, which isn't recommended by Apple.)


RegexKit is the best I've found yet. Very Cocoa:y. I'm using the "Lite" version in several of our iPhone apps:

sourceforge

lingonikorg