我坚持定义这种模式,它将产生我所寻找的结果。任何帮助都将不胜感激。
NSError *regexError = nil;
NSRegularExpression *parsingRegex = [NSRegularExpression regularExpressionWithPattern:@"(vector)\\((.*?)(?:,\\s*(.*?))*\\)"
options:0
error:®exError];
NSString *mystring = @"vector(0.1, 0.0, 0.0, 1.0)";
NSTextCheckingResult *parse = [parsingRegex firstMatchInString:mystring
options:0
range:NSMakeRange(0, [string length])];
NSLog(@"string0 =%@\n"[mystring substringWithRange:[parse rangeAtIndex:0]]);
NSLog(@"string1 =%@\n"[mystring substringWithRange:[parse rangeAtIndex:1]]);
NSLog(@"string2 =%@\n"[mystring substringWithRange:[parse rangeAtIndex:2]]);
NSLog(@"string3 =%@\n"[mystring substringWithRange:[parse rangeAtIndex:3]]);
NSLog(@"string4 =%@\n"[mystring substringWithRange:[parse rangeAtIndex:4]]);
NSLog(@"string4 =%@\n"[mystring substringWithRange:[parse rangeAtIndex:5]]);我希望得到以下输出:
string0 = vector(0.1, 0.0, 0.0, 1.0)
string1 = vector
string2 = 0.1
string3 = 0.0
string4 = 0.0
string5 = 1.0我得到以下输出:
string0 = vector(0.1, 0.0, 0.0, 1.0)
string1 = vector
string2 = 0.1
string3 = 1.0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSExtendedRegularExpressionCheckingResult rangeAtIndex:]: index 4 out of range'谢谢
所以这是可行的:
模式是:
NSRegularExpression *parsingRegex = [NSRegularExpression
regularExpressionWithPattern:@"(vector)\\((.*?)(?:,\\s*(.*?))(?:,\\s*(.*?))(?:,\\s*(.*?))*\\)"
options:0
error:®exError];但仅当字符串为
NSString *mystring = @"vector(0.1, 0.0, 0.0, 1.0)";如果字符串为:
NSString *mystring = @"value(0.1)";我预料到了:
NSRegularExpression *parsingRegex = [NSRegularExpression
regularExpressionWithPattern:@"(vector|value)\\((.*?)(?:,\\s*(.*?))(?:,\\s*(.*?))(?:,\\s*(.*?))*\\)"
options:0
error:®exError];
NSLog(@"string0 =%@\n"[mystring substringWithRange:[parse rangeAtIndex:0]]);
NSLog(@"string1 =%@\n"[mystring substringWithRange:[parse rangeAtIndex:1]]);
NSLog(@"string2 =%@\n"[mystring substringWithRange:[parse rangeAtIndex:2]]);将会工作并返回
string0 = value(0.1)
string1 = value
string2 = 0.1但事实并非如此。
有什么想法吗?
发布于 2013-12-27 03:17:45
(vector)\((.*?)(?:,\s*(.*?))*\)有3个捕获组。它永远不会有更多。
(vector)\(([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^)\s]+)\s*\)更接近你想要的。
https://stackoverflow.com/questions/20789867
复制相似问题