【问题标题】:NSRegularexpression multiline and stackNSRegularexpression 多行和堆栈
【发布时间】:2013-04-16 10:44:50
【问题描述】:

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

我无法匹配开始标签对应的结束标签,例如 {{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]]);
    }

【问题讨论】:

    标签: ios regex nsregularexpression


    【解决方案1】:

    你可以使用这个模式

    \{\{([^/]*?)\}\}(.*?)\{\{(/\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
    

    【讨论】:

    • 感谢您的帮助,我不知道/找到组的概念。它运行良好,只是我对多列表进行了一些更改:@"\\{\\{([^/]*?)\\}\\}" ".*?" (这里是变化)“\\{\\{((/\\1)|(//))\\}\\}”
    猜你喜欢
    • 2010-12-29
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 2021-12-08
    • 2023-03-20
    • 2016-04-20
    • 1970-01-01
    相关资源
    最近更新 更多