我很难定义那种能产生我想要的结果的模式。 任何帮助将不胜感激。
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
但事实并非如此。
任何想法?
答案 0 :(得分:0)
(vector)\((.*?)(?:,\s*(.*?))*\)
有3个捕获组。它将永远不会有更多。
(vector)\(([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^)\s]+)\s*\)
更接近你想要的。