Skip to content

Commit

Permalink
Merge pull request #5 from justinmakaila/master
Browse files Browse the repository at this point in the history
Added method for checking for matches within the receiver with a regex
  • Loading branch information
khanlou committed Jun 3, 2014
2 parents 6b9b0aa + fcbf58c commit 14511c6
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
9 changes: 9 additions & 0 deletions Objective-Shorthand/Objective-Shorthand/NSString+Regex.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,13 @@
*/
- (NSRange) rangeOfFirstSubstringMatching:(NSString*)regex;

/**
* Returns an array of NSTextMatchingResults within the receiver
*
* @param regex The regular expression pattern to match against.
*
* @return An array of NSTextMatchingResults containing the matches from the receiver.
*/
- (NSArray*) matchesForRegex:(NSString*)regex;

@end
9 changes: 6 additions & 3 deletions Objective-Shorthand/Objective-Shorthand/NSString+Regex.m
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@
@implementation NSString (Regex)

- (BOOL) matchesRegex:(NSString*)regex {
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regex options:0 error:nil];
NSUInteger numberOfMatches = [regularExpression numberOfMatchesInString:self options:0 range:NSMakeRange(0, self.length)];
return numberOfMatches > 0;
return ([self matchesForRegex:regex].count > 0);
}

- (NSRange) rangeOfFirstSubstringMatching:(NSString*)regex {
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regex options:0 error:nil];
return [regularExpression rangeOfFirstMatchInString:self options:0 range:NSMakeRange(0, self.length)];
}

- (NSArray*) matchesForRegex:(NSString *)regex {
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regex options:0 error:nil];
return [regularExpression matchesInString:self options:0 range:NSMakeRange(0, self.length)];
}

@end
9 changes: 9 additions & 0 deletions Objective-ShorthandTests/SKRegexCategoryTest.m
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,13 @@ - (void)testNonexistentMatch
XCTAssertFalse(doesMatch, @"the string test should not be found");
}

- (void)testMultipleMatches {
// Finds all of the matches for a hashtag
NSString *testString = @"@justin is gonna make this #work #srsly #sickofthisnotbeingathing";

NSArray *matches = [testString matchesForRegex:@"#(\\w+)"];

XCTAssert(matches.count == 3, @"Could not find the 3 provided hashtags");
}

@end

0 comments on commit 14511c6

Please sign in to comment.