Objective c Objc Regex-使用组解析字符串
我试图在“:”之前和之后解析文本文件和组信息,这样我就可以知道什么与什么相关 我正在使用下面的Objective c Objc Regex-使用组解析字符串,objective-c,regex,nsregularexpression,Objective C,Regex,Nsregularexpression,我试图在“:”之前和之后解析文本文件和组信息,这样我就可以知道什么与什么相关 我正在使用下面的 //NSString *pattern = @"\\[(.*?)\\]"; //[] //NSString *pattern = @"(\\w+:)"; //word: NSString *pattern =@"(\\w+:)\\[(.*?)\\]"; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPatt
//NSString *pattern = @"\\[(.*?)\\]"; //[]
//NSString *pattern = @"(\\w+:)"; //word:
NSString *pattern =@"(\\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]);
}
“[]”和“单词:”起作用,但当我把它们连在一起时,我什么也得不到
括号(输出)
字(输出)
我在模式中遗漏了什么
NSString *pattern =@"(\\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]
由于您需要将每个“单词”与其对应的
[…]
进行匹配,因此可以使用包含2个捕获组的正则表达式模式和将“调节”惰性点匹配模式的前瞻:
@"(?s)(\\w+):\\s*\\[(.*?)\\](?=,\r?\n\\s*\\w+:|$)"
见
模式匹配:
-启用(?s)
以匹配换行符
-将一个或多个字母数字字符匹配并捕获到组1中,然后匹配(\w+):
:
-0+空格字符\s*
-匹配\[(.*)\]
捕获组1中的所有内容(如果最后一个[…]
]
-后跟字符串结尾((?=,\r?\n\s*\w+:|$)
),或逗号后跟换行符,后跟0+空格符号,后跟“word”,后跟$
:
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]
@"(?s)(\\w+):\\s*\\[(.*?)\\](?=,\r?\n\\s*\\w+:|$)"