2016-03-26 19 views
1

我試圖解析「:」前後的文本文件和組信息,以便我可以知道什麼與什麼有關。Objc正則表達式 - 與組分析字符串

我使用以下

//NSString *pattern = @"\\[(.*?)\\]"; //[] 
//NSString *pattern = @"(\\w+:)"; //word: 
NSString *pattern [email protected]"(\\w+:)\\[(.*?)\\]"; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil]; 
NSString *input = contents; //contents being the value taken from the text file 

NSMutableArray *matches = [NSMutableArray arrayWithCapacity:[myArray count]]; 
for (NSTextCheckingResult *match in myArray) { 
    //NSUInteger numberOfRanges = [match numberOfRanges]; 
    //NSLog(@"%lu", (unsigned long)numberOfRanges); 
    NSRange matchRange = [match rangeAtIndex:1]; 
    [matches addObject:[input substringWithRange:matchRange]]; 
    NSLog(@"%@", [matches lastObject]); 
} 

的「[]」工程和「詞:」作品,但是當我加入他們在一起我什麼也沒有回來。

支架(輸出)

2016-03-26 09:20:36.302 LevelBuilder[14658:550234] 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1 
... 
2016-03-26 09:20:36.304 LevelBuilder[14658:550234] 17,1 

字(輸出)

2016-03-26 09:18:18.189 LevelBuilder[14464:543898] tiles: 
2016-03-26 09:18:18.189 LevelBuilder[14464:543898] boxes: 
2016-03-26 09:18:18.189 LevelBuilder[14464:543898] goals: 
2016-03-26 09:18:18.189 LevelBuilder[14464:543898] start: 

什麼我在圖案

NSString *pattern [email protected]"(\\w+:)\\[(.*?)\\]"; 

的數據是一個例子

tiles: 
    [ 
     [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1] 
     ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1] 
     ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1] 
     ,[0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,1,0,0,1] 
     ,[1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,1] 
     ,[1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1] 
     ,[1,0,0,0,0,0,0,1,1,1,0,0,1,1,1,0,0,0,1] 
     ,[1,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1] 
     ,[1,0,0,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,1] 
     ,[1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1] 
     ,[1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 
     ,[1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 
     ,[1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 
    ], 
    boxes: [ 
      [5,6],[6,5],[10,5],[11,5],[16,4],[16,5],[16,6],[16,7] 
      ], 
    goals: [ 
      [1,8],[1,9],[1,10],[1,11],[2,10],[2,11],[3,10],[3,11] 
      ], 
    start: [17,1] 
失蹤
+1

這不是很清楚。也許你需要['(?s)(\\ w +:)\\ s * \\ [。*?\\](?=,\ r?\ n | $)'](https://regex101.com/R/sT5oA9/1)? –

+0

Thanks @WiktorStribiżew這是他們作爲4個人匹配 –

+0

這是否意味着你正在尋找這個解決方案? –

回答

1

既然你需要匹配每個「單詞」後面與其對應的[...],您可以使用包含2個捕獲組正則表達式模式和前瞻將要「脾氣」懶點匹配模式:

@"(?s)(\\w+):\\s*\\[(.*?)\\](?=,\r?\n\\s*\\w+:|$)" 

見所述regex demo

的模式匹配:

  • (?s) - 使.匹配換行符
  • (\w+): - 比賽並捕捉到第1個的一個或多個字母數字字符,然後匹配:
  • \s* - 0+空格字符
  • \[(.*?)\] - 匹配[...]捕獲所有的裏面是什麼進組1如果最後] ...
  • (?=,\r?\n\s*\w+:|$) - 後跟字符串的結尾($)或逗號後跟一個換行符,後跟0+個空白符號,後跟一個「word」,後跟: