0

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

"Key" = "Value";

以下代码用于提取“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";

有没有任何有效的方法来执行这种解析的解析?

4

2 回答 2

1

我不熟悉那种方言,但既然你已经标记regex了 ,那么原则上应该这样做:^"([^"]*)" = "([^"]*)";$

您对格式并不准确,因此您可能需要根据您的输入格式在这里和那里添加一些条件空格。可能会起作用的另一件事是需要转义括号。

例如sed,您必须编写:

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

于 2013-09-05T09:55:21.503 回答
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]);
于 2013-09-05T11:28:46.380 回答