1

我找不到具有平衡标签的正则表达式,一个用于打开,一个用于关闭。标签必须包含多行文本;和标签是动态的,不是在编译时定义的

我无法匹配开始标签对应的结束标签,例如 {{home}} -> {{/home}} 和 {{hello}} -> {{/hello}};它匹配 {{home}} 到 {{/hello}} 任何帮助将不胜感激

任何帮助将不胜感激

格雷戈里

ps:我评论了非工作正则表达式

    NSString * string;
    NSError* error = nil;
    NSRegularExpression* regex;
    NSArray* matches;


    string =
    @" The {{demo}}following tables describe the {{/demo}}character expressions"
    " used by the regular expression to match patterns within "
    " a string,{{home}} the pattern operators that specify how many"
    " times a pattern is matched and additional matching"
    " restrictions, and the last {{/home}}table specifies flags"
    " that can be included in the regular ";


    regex = [NSRegularExpression regularExpressionWithPattern:
             @"\\{\\{demo\\}\\}"
             "(.*)?"
             "\\{\\{(//|/demo)\\}\\}"
                                                      options:NSRegularExpressionDotMatchesLineSeparators
                                                        error:&error];


//    regex = [NSRegularExpression regularExpressionWithPattern:
//             @"\\{\\{.*\\}\\}"
//             "(.*)?"
//             "\\{\\{(//|/.*)\\}\\}"
//                                                      options:NSRegularExpressionDotMatchesLineSeparators
//                                                        error:&error];


    matches = [regex matchesInString:string
                             options:NSRegularExpressionDotMatchesLineSeparators
                               range:NSMakeRange(0, [string length])];

    for ( NSTextCheckingResult* match in matches )
    {
        NSLog(@"### %@ ###", [string substringWithRange:[match range]]);
    }
4

1 回答 1

0

您可以使用此模式

\{\{([^/]*?)\}\}(.*?)\{\{(/\1|//)\}\}
    -------     ----     --------
       |          |          |->matches closing tag having value same as group 1 or //
       |          |->content in group 2
       |->matches the opening tag value and captures it in group1
于 2013-04-16T10:56:02.530 回答