Regular expressions in an Objective-C Cocoa application

Viewed 78275

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?

10 Answers
  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

You can use the POSIX Regular Expressions library (Yay for a POSIX compliant OS). Try

man 3 regex

I like the AGRegex framework which uses PCRE, handy if you are used to the PCRE syntax. The best version of this framework is the one in the Colloquy IRC client as it has been upgraded to use PCRE 6.7:

http://colloquy.info/project/browser/trunk/Frameworks/AGRegex

It's very lightweight, much more so than RegExKit (although not as capable of course).

During my search on this topic I came across CocoaOniguruma which uses Oniguruma, the Regular Expression engine behind Ruby1.9 and PHP5. It seems a bit newer compared to the existing OregKit (in Japanese). Not sure how these stack up against other bindings.

Googling alittle, found this library: RegexOnNSString

Open source library, containing functions like:

-(NSString *) stringByReplacingRegexPattern:(NSString *)regex withString:(NSString *) replacement caseInsensitive:(BOOL)ignoreCase

and using NSRegularExpression class. Quite easy to use and no need to worry about anything.

Please, note that NSRegularExpression is available since Mac OS X v10.7 and IOS 4.0, as Datasmid mentioned.

Related