簡體   English   中英

NSRegularExpression模式

[英]NSRegularExpression Pattern

我堅持定義那種模式,它將產生我想要的結果。 任何幫助將不勝感激。

NSError *regexError = nil;
NSRegularExpression *parsingRegex = [NSRegularExpression regularExpressionWithPattern:@"(vector)\\((.*?)(?:,\\s*(.*?))*\\)"
                                            options:0
                                            error:&regexError];

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:&regexError];

但僅當字符串為

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:&regexError];


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

但事實並非如此。

有任何想法嗎?

(vector)\\((.*?)(?:,\\s*(.*?))*\\)有3個捕獲組。 它再也沒有了。

(vector)\\(([^,\\s]+)\\s*,\\s*([^,\\s]+)\\s*,\\s*([^,\\s]+)\\s*,\\s*([^,\\s]+)\\s*,\\s*([^)\\s]+)\\s*\\)更接近您想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM