regex

Using Regular Expressions Part 2 - The Cocoa Connection

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:

myString.sub(‘pattern’,‘replacement’)

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.

 7 min read

Using Regular Expressions and Retaining your Sanity

At a recent Austin, Texas Cocoacoder meeting, I made an offhand comment giving someone a regular expression that would help with a problem they were having. That led to two things. First, I was asked to put together a presentation (which I’ve been working on) on using regular expressions to give at an upcoming CocoaCoder meeting, and second, I was asked why on Earth anyone would use something as opaque and unmaintainable as a regular expression in this day and age.

 5 min read