以stackOverFlow上的問題為例子:Extracting single values from a parsed NSString in objective-c
NSString *string = @"The name of first value, first 17/04/2013 11:30:00 - A:30.0";
NSString *pattern = @"(.*) (\\d{2}/\\d{2}/\\d{4} \\d{2}:\\d{2}:\\d{2}) - A:(.*)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if (match != nil) {
NSString *s1 = [string substringWithRange:[match rangeAtIndex:1]];
NSString *s2 = [string substringWithRange:[match rangeAtIndex:2]];
NSString *s3 = [string substringWithRange:[match rangeAtIndex:3]];
NSLog(@"First part: %@", s1);
NSLog(@"Second part: %@", s2);
NSLog(@"Third part: %@", s3);
}
- (.*):.(句點)表示除了\r\n(換行)以外的字元,後面加上*表示>=0。整個的意思是任何不是換行的字元都會匹配到,直到遇到匹配後面的語法為止
- 在括弧之間的空格也會被當作判斷之一
- 不在括弧內的匹配會被過濾掉
- 一般的表達式用\d代表數字,在objective c上會被以為是跳脫字元,因此要再多加一個\,就是要變成\\d這樣用
- {2}代表要剛好2個字元
- 它用來劃分range的標準是用括弧判斷,上面的code三個括弧對到三個match
- 上面沒提到的語法像是[rwx]+ 等等也是支援的
沒有留言:
張貼留言