解析“Key”=“Value”对

时间:2013-09-05 07:47:34

标签: objective-c regex nsregularexpression

我试图使用正则表达式以下面的格式解析字符串:

"Key" = "Value";

以下代码用于提取"键"和"价值":

NSString* pattern = @"([\"\"'])(?:(?=(\\\\?))\\2.)*?\\1";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                       options:0
                                                                         error:NULL];
NSRange matchRange = NSMakeRange(0, line.length);
NSTextCheckingResult *match = [regex firstMatchInString:line options:0 range:matchRange];
NSRange rangeKeyMatch = [match rangeAtIndex:0];

matchRange.location = rangeKeyMatch.length;
matchRange.length = line.length - rangeKeyMatch.length;
NSTextCheckingResult *match2 = [regex firstMatchInString:line options:0 range:matchRange];
NSRange rangeValueMatch = [match2 rangeAtIndex:0];

它看起来效率不高,并没有将以下示例视为无效:

"key" = "value" = "something else";

有没有有效的方法来解析这种解析?

2 个答案:

答案 0 :(得分:1)

我对这种方言并不熟悉,但由于你标记了regex,所以原则上应该这样做:^"([^"]*)" = "([^"]*)";$

您对格式不确切,因此您可能需要根据输入格式在此处添加一些条件空白区域。可能发挥作用的另一件事是需要逃避括号。

例如sed,你必须写:

echo '"Key" = "Value";' | sed -e 's#^"\([^"]*\)" = "\([^"]*\)";$#key is \1 and value is \2#'

答案 1 :(得分:1)

此代码应与"key" = "value"匹配,而不是"key" = "value" = "something else"

NSString *line = @"\"key\" = \"value\"";

NSError *error = NULL;
NSString *pattern = @"\\\"(\\w+)\\\"\\s=\\s\\\"(\\w+)\\\"$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                       options:NSRegularExpressionAnchorsMatchLines error:&error];
NSRange matchRange = NSMakeRange(0, line.length);
NSTextCheckingResult *match = [regex firstMatchInString:line options:0 range:matchRange];

/* It looks like you were not quite looking at the ranges properly. The rangeAtIndex 0 is actually the entire string. */
NSRange rangeKeyMatch = [match rangeAtIndex:1];
NSRange rangeValueMatch = [match rangeAtIndex:2];

NSLog(@"Key: %@, Value: %@", [line substringWithRange:rangeKeyMatch], [line substringWithRange:rangeValueMatch]);