Skip to content

Instantly share code, notes, and snippets.

@MichaelSnowden
Created May 12, 2014 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelSnowden/e5badcffeb7c4300d067 to your computer and use it in GitHub Desktop.
Save MichaelSnowden/e5badcffeb7c4300d067 to your computer and use it in GitHub Desktop.
NSString *pattern = @"[A-Z][a-z]?\\d*|(?<!\\([^)]*)\\(.*\\)\\d+(?![^(]*\\))";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:0
error:nil];
NSArray *tests = [[NSArray alloc ] initWithObjects:@"Ca3(PO4)2", @"HCl", @"CaCO3", @"ZnCl2", @"C7H6O2", @"PtCl2(NH3)2", @"Co3(Fe(CN)6)2", nil];
for (NSString *testString in tests)
{
NSLog(@"Testing: %@", testString);
NSArray *myArray = [regex matchesInString:testString options:0 range:NSMakeRange(0, [testString length])] ;
NSMutableArray *matches = [NSMutableArray arrayWithCapacity:[myArray count]];
for (NSTextCheckingResult *match in myArray) {
NSRange matchRange = [match rangeAtIndex:0];
[matches addObject:[testString substringWithRange:matchRange]];
NSLog(@"%@", [matches lastObject]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment