Last time, in Part 1 of this series, I wrote about the basics of regular expressions, and the phrases I tend to use. Today, I’m going to talk about the mechanics of how I use Regular Expressions in Cocoa.
##But first, an historical diversion
In my opinion there are, two different ways that programming languages implement Regular Expressions: The perl/ruby way, and the Java/C#/Python/Cocoa way.
In ruby and perl, regexes are implemented directly on the String type, whereas in the other languages, there a separate object that contains the functionality. Here’s what you need to know to do a regex substitution on a string in ruby:
clean, easy, and immediately useable if you know what pattern you want to use.
Here’s what you need to know to do the same thing in Cocoa:
+[NSRegularExpression regularExpressionWithPattern:(NSString *) pattern options:(NSRegularExpressionOptions)options error:(NSError **) error] -[NSRegularExpression replaceMatchesInString:(NSMutableString *) string options:(NSMatchingOptions)options range:(NSRange)range withTemplate:(NSString *)template]
which is not clean, not easy and contains a bunch of stuff you have to go look up to be able to get started. What are NSRegularExpressionOptions and
NSMatchingOptions? What’s a template? Do I really have to create an
NSRange for this? And that leads to the obvious question: Is all this effort really worth it?
Now I don’t know about you, but I don’t want to spend any effort remembering any of those option parameters, and I don’t want to take the time to look them up any time I want to use a regular expression. To me, the beauty of Objective-C is that it gives us the ability to build most of what you need to know directly into the method signatures.Published at October 15, 2011 · 7 min read