2013-04-16 46 views
0

我無法找到具有平衡標籤的正則表達式,一個用於打開,一個用於關閉。 標籤必須包含多行文字;並且標記是動態的,在編譯時未定義NSRegularexpression multiline and stack

我無法匹配與開始標記對應的結束標記,例如{{home}} - > {{/ home}}和{{hello}} - > {{/ 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]]); 
    } 

回答

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 
+0

感謝您的幫助,我不知道/發現羣體的概念。除了我爲多個用戶做了一些修改之外,它運行良好:@「\\ {\\ {([^ /] *?)\\} \\}」 「。*?」 (這是變化) 「\\ {\\ {((/ \\ 1)|(//))\\} \\}」 –

+0

它的工作方式就像一個魅力,謝謝 –