Skip to content

Instantly share code, notes, and snippets.

@jkereako
Last active August 29, 2015 14:14
Show Gist options
  • Save jkereako/3d0a9e2a4cc531a575a0 to your computer and use it in GitHub Desktop.
Save jkereako/3d0a9e2a4cc531a575a0 to your computer and use it in GitHub Desktop.
Use this code snippet to test your regular expression syntax.
//
// regex-tester.m
// Alexis Digital
//
// Created by Jeff Kereakoglow on 1/23/15.
//
// Use this code snippet to test your regular expression syntax.
//
#import <Foundation/Foundation.h>
int main(int argc, const char *argv[]) {
@autoreleasepool {
NSString *regex;
NSString *text;
NSPredicate *predicate;
BOOL isValid = NO;
// Get the command-line arguments
if([NSProcessInfo processInfo].arguments.count >= 3) {
regex = [NSProcessInfo processInfo].arguments[1];
text = [NSProcessInfo processInfo].arguments[2];
predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
isValid = [predicate evaluateWithObject:[text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSLog(@"\n\n Regex: %@\n Text: %@\n Result: %@\n\n", regex, text, ((isValid) ? @"Valid" : @"Invalid"));
}
else {
NSLog(@"\n\n Not enough arguments");
}
}
return 0;
}
@jkereako
Copy link
Author

Description

I have a hard time writing regular expressions that are compatible with Cocoa. I wrote this small program to quickly test to see if my syntax is correct.

Compilation

Compile with this command

clang -fobjc-arc regex-tester.m -o regex-tester

And execute with this command

$ .\regex-tester ^(your|regex)$ The text you want to match against

To see this result

$ ./regex-tester ^\\d$ 0
2015-01-23 15:38:08.567 regex[11219:219404] 

 Regex:  ^\d$
 Text:   0
 Result: Valid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment