PCRE for iPhone

Lately, I’ve been working on a project requiring heavy use of regular expressions on Cocoa. Foundation frameworks do not offer built in support for regular expressions. Instead, they do heavy work using NSScanner, and NSPredicate classes.

 A framework was created to solve this problem, called RegexKitLite, but it’s heavy use of and linking to Apple’s internal ICU framework, makes it very dangerous to App Store Rejection, when talking about applications for iPhone.

So, I’ve been searching for something like PCRE for iPhone, and I couldn’t find it anywhere. Therefore, I downloaded, and compiled the famous and standard PCRE library for  the iPhone as a dylib. I know that for some of you this can be a difficult process, so I will describe the steps here.

 Making PCRE for iPhone

Download the latest version PCRE library source from here. Extract the file, so that you have only a folder containing many sources. DO NOT RUN THE CONFIGURE FILE! We will be using our home-made script to do all the dirty work and set the correct environment variables to ensure that the library will be build correctly and can be embedded in an iPhone application.

Open a new plain text file, and paste the following script inside:

 #!/bin/bash

# Compile a PCRE version for the iphone device

CC=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc
CPP=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/cpp
AR=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/ar
./configure –disable-shared –host=arm-apple-darwin –disable-cpp
CFLAGS=”-arch armv6 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk”

make

#and now cleanup and make a folder with the necessary components

rmdir ~/Dekstop/pcre_iphone
mkdir ~/Desktop/pcre_iphone
mv .libs/libpcre.a ~/Desktop/pcre_iphone/libpcre_device.a
cp ./pcre.h ~/Desktop/pcre_iphone/pcre.h

Save it in the same folder with the PCRE sources as “pcre_iphone.sh”. This step is important. Do not save it anywhere else.This is the script you will be running from the terminal to compile the source. One last step remains before you can execute the script. Your newly created script does not have “execut” permissions!

So, open Terminal and type:

cd ~/Path_To_PCRE_Folder
chmod U+x

OK, now your script is executable. Now, type in the terminal:

./pcre_iphone.sh

You will be seeing lots and lots of lines of code as GCC uses the iPhone Device’s SDK to build the PCRE library as a static library (.a). Upon success, the script will copy the resulting library AND the Library’s header (“pcre.h”) to a folder named “pcre_iphone” on your desktop.

Now, you are ready to use the PCRE library in your project. Just create a new project, drag both the .a library and the header file in your project, and sart using the library as you would use it an any other project.