shhhhh, don't tell anybody
pyobjc is nice for introspection of cocoa objects. :)
NSString has some private regexp methods. Not so surprising, given that coredata lets us validate strings against regular expressions... As always with hidden functionality in apple classes: this might not always work the way you expect and might not even exist in past / future versions of the os...etc.
(UPDATE: this doesn't really behave as I would have expected. See code in the comments that does).
#import <Foundation/Foundation.h>int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];NSString *test = [[NSString alloc] initWithString:@"hello world"];
NSString *regexp = [[NSString alloc] initWithString:@"hello*"];
if ([test matchesPattern:regexp]) {
NSLog(@"%@ Matches %@", test, regexp);
} else {
NSLog(@"%@ Does not match %@", test, regexp);
}
[test release];
[regexp release];
[pool release];
return 0;
}
[Session started at 2006-08-27 15:01:02 -0400.]
2006-08-27 15:01:02.975 nsstringtest[2239] hello world Matches hello*
nsstringtest has exited with status 0.
Comments
The method I found doesn't really work as expected with more complex regular expressions. I found another way. Let's use a NSPredicate!
[Session started at 2006-08-29 00:59:24 -0400.]
2006-08-29 00:59:24.700 nsstringtest[11115] 123.255.255.255 Matches (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
2006-08-29 00:59:24.700 nsstringtest[11115] It works
nsstringtest has exited with status 0.
Posted by: jonathan | August 29, 2006 10:47 AM