There are several instances when we need to search for specific type of text in a string or document. For example, searching for a URL in a HTML file, confirming e-mail address in a web form field and so on.

The easiest way to get around this is by using an open source library called: Regex. Regex is an efficient and quick way to implement Regular expression search in Objective-C.

All you need to do is follow the given steps:

1. Download the source code.

2. In Xcode,

Go to Project -> Edit Active Target.

Select Build from the tab near the top of the Target Info window. Find the Other Linker Flags build setting from the many build settings available and edit it. Add -licucore [dash ell icucore as a single word, without spaces]. If there are already other flags present, it is recommended that you add -licucore to the end of the existing flags.

3. Now add the RegexKitLite.h and RegexKitLite.m files to your project directory.

4. #import “RegexKitLite.h” in the file where you want to implement the search.

5. Lastly, create a Regular expression string and match it with the given string using the method: componentsMatchedByRegex

For example, for searching for a URL:

NSString *urlRegex = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
NSArray *matchedURLsArray = [str componentsMatchedByRegex:urlRegex];
NSLog(@"matchedURLsArray: %@", matchedURLsArray);

Similarly, for some other Network and URL regular expressions:

http://regexkit.sourceforge.net/RegexKitLite/index.html#RegexKitLiteCookbook_PatternMatchingRecipes_NetworkandURL

For any other type of Regular Expressions:

http://regexkit.sourceforge.net/RegexKitLite/index.html#ICUSyntax

Sphere: Related Content

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.