【发布时间】:2014-05-12 06:14:26
【问题描述】:
我需要一种方法来将化学式分解为其组成部分。结果应该看起来像 这个:
Ag3PO4 -> [Ag3, P, O4]
H2O -> [H2, O]
CH3OOH -> [C, H3, O, O, H]
Ca3(PO4)2 -> [Ca3, (PO4)2]
我不知道正则表达式的语法,但我知道我需要这样的东西
[可选括号][大写字母][0个或多个小写字母][0个或多个数字][可选括号][0个或多个数字]
成功了
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"[A-Z][a-z]*\\d*|\\([^)]+\\)\\d*"
options:0
error:nil];
NSArray *tests = [[NSArray alloc ] initWithObjects:@"Ca3(PO4)2", @"HCl", @"CaCO3", @"ZnCl2", @"C7H6O2", @"BaSO4", 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]);
}
}
【问题讨论】:
-
我不确定化学公式是否是常规语言。你也许可以尝试一下,但它可能并不完美。
-
@LegoStormtroopr 看看我上面的尝试,只要我能得到类似的东西,我就会很酷。
标签: objective-c regex