[英]iOS Split NSString with Regular Expression
我正在使用此代碼來解析NSString
:
NSString *string = @"{{nat fs g player|no=1|pos=GK|name=[[Hugo Lloris]]|age={{Birth date and age|1986|12|26|df=y}}|caps=73|goals=0|club=[[Tottenham Hotspur F.C.|Tottenham Hotspur]]|clubnat=ENG}}";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{nat fs g player\\|no=(.*)\\|pos=(.*?)\\|name=\\[\\[(.*?)\\]\\]\\|age=\\{\\{Birth date and age\\|(.*?)\\|(.*?)\\|(.*?)\\|df=y\\}\\}\\|caps=(.*?)\\|goals=(.*?)\\|club=\\[\\[(.*?)\\|(.*)"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *matches = [regex matchesInString:string
options:0
range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
NSString *a = [string substringWithRange:[match rangeAtIndex:0]];
NSString *b = [string substringWithRange:[match rangeAtIndex:1]];
NSString *c = [string substringWithRange:[match rangeAtIndex:2]];
NSString *d = [string substringWithRange:[match rangeAtIndex:3]];
NSString *e = [string substringWithRange:[match rangeAtIndex:4]];
NSString *f = [string substringWithRange:[match rangeAtIndex:5]];
NSString *g = [string substringWithRange:[match rangeAtIndex:6]];
NSString *h = [string substringWithRange:[match rangeAtIndex:7]];
NSString *i = [string substringWithRange:[match rangeAtIndex:8]];
NSString *j = [string substringWithRange:[match rangeAtIndex:9]];
NSString *k = [string substringWithRange:[match rangeAtIndex:10]];
}
使用此代碼我真的得到了數據,但是當我試圖用相同的模式分割2個字符串時:
NSString *string = @"{{nat fs g player|no=1|pos=GK|name=[[Hugo Lloris]]|age={{Birth date and age|1986|12|26|df=y}}|caps=73|goals=0|club=[[Tottenham Hotspur F.C.|Tottenham Hotspur]]|clubnat=ENG}}{{nat fs g player|no=16|pos=GK|name=[[Steve Mandanda]]|age={{Birth date and age|1985|3|28|df=y}}|caps=21|goals=0|club=[[Olympique de Marseille|Marseille]]|clubnat=FRA}}";
我只得到一場比賽,任何想法為什么?
您需要修復正則表達式以允許部分匹配。
由於記錄以}}
結尾,因此請在最后一個捕獲組中使用lazy (.*?\\}\\})
。
正則表達式聲明將是:
NSString *pattern = @"\\{\\{nat fs g player\\|no=([^|]*)\\|pos=([^|]*)\\|name=\\[\\[([^|]*)\\]\\]\\|age=\\{\\{Birth date and age\\|([^|]*)\\|([^|]*)\\|([^|]*)\\|df=y\\}\\}\\|caps=([^|]*)\\|goals=([^|]*)\\|club=\\[\\[([^|]*)\\|(.*?\\}\\})";
請參閱IDEONE演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.