Get Updates By E-mail 

Article Written By:
Johann Dowa

NSRegularExpression Category With An Extensive Number Of Helpers For Easier Regular Expressions


Remembering all the little details for creating regular expressions can be frustrating – especially if it’s not something that you do every day.

Early this year I mentioned a handy tool for testing NSRegularExpression regular expressions and a few months ago mentioned a library providing an alternative to NSRegularExpression with a verbal syntax for constructing your queries.

Here’s a library that provides an extensive number of add-ons for NSRegularExpression called Objective-C-RegEx-Categories from BendyTree.

The library includes macros for shortening your code, and helpers for testing, finding matches, replacing text and more.

Here’s a set of examples from the readme showing some of the helpers included in Objective-C-RegEx Categories in action:

//Create an NSRegularExpression
Rx* rx = RX(@"\\d");
Rx* rx = [Rx rx:@"\\d"];
Rx* rx = [Rx rx:@"\\d" ignoreCase:YES];

//Test if a string matches
BOOL isMatch = [@"2345" isMatch:RX(@"^\\d+$")];

//Get first match
NSString* age = [@"My dog is 3." firstMatch:RX(@"\\d+")];

//Get matches as a string array
NSString* words = [@"Hey pal" firstMatch:RX(@"\\w+")];
// words => @[ @"Hey", @"pal" ]

//Get first match with details
RxMatch* match = [@"12.34, 56.78" firstMatchWithDetails:RX(@"\\d+([.]\\d+)")];
// match.value => @"12.34"
// match.range => NSRangeMake(0, 5);
// match.original => @"12.34, 56.78";
// match.groups => @[ RxMatchGroup, RxMatchGroup ];

//Replace with a template string
NSString* result = [@"My dog is 12." replace:RX(@"\\d+") with:@"old"];
// result => @"My dog is old."

//Replace with a block
NSString* result = [RX(@"\\w+") replace:@"hi bud" withBlock:^(NSString* match){
  return [NSString stringWithFormat:@"%i", match.length];
// result => @"2 3"

//Replace with a block that has the match details
NSString* result = [RX(@"\\w+") replace:@"hi bud" withDetailsBlock:^(RxMatch* match){
  return [NSString stringWithFormat:@"%i", match.value.length];
// result => @"2 3"


You can find Objective-C-RegEx-Categories on Github here.

A very nice library for simplifying your work with NSRegularExpression.


Submit A Resource

Have you created a useful tutorial, library or tool for iOS development that you would like to get in front of our 300,000+ monthly page views from iOS developers?

You can submit the url here.

The resources we feel will appeal to our readers the most will be posted on the front page.