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:
Is that really true?
Are you kidding me?
Ok, then is there a nice open-source library you recommend?
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.
- 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.
- 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).
- There are many OSS libraries, CocoaDev has an extensive list.
-
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