【问题标题】:Parsing "Key" = "Value" pair解析“键”=“值”对
【发布时间】:2013-09-05 07:47:33
【问题描述】:

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

"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";

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

【问题讨论】:

    标签: objective-c regex nsregularexpression


    【解决方案1】:

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

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

    例如sed,你必须写:

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

    【讨论】:

    • NSRegularExpression 跟随the ICU standard,以防人们感兴趣。啊,为了使模式更加健壮,我会使用 \s+ 代替单个空格。
    【解决方案2】:

    此代码应匹配 "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]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-18
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多