我有要读取的varius日志文件。每个日志都包含设备(打印机)的报告。 我能找到的始终是'固件:'然后是固件版本,如:
PTRE firmware: XER8673B2
日志似乎没有非常有序,因此该文本的位置并不总是在同一点或同一行,而是始终在" PTRE firmawre:XXXXXXX"格式。 我怎样才能找到XER8673B2?任何帮助表示赞赏。
已解决(感谢@ roman-sausarnes),这是代码:
NSString *stringToSearch = [[NSString alloc] initWithContentsOfFile:@"path/to/log" encoding:NSUTF8StringEncoding error:nil];
NSString *preMatchString = @"PTRE firmware: ";
NSString *terminatingCharacter = @" ";
NSString *result = [[NSString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:stringToSearch];
[scanner scanUpToString:preMatchString intoString:NULL];
[scanner scanString:preMatchString intoString:NULL];
[scanner scanUpToString:terminatingCharacter intoString:&result];
NSLog(@"It's : %@", result);
输出
It's : XER8673B2
答案 0 :(得分:1)
看看NSScanner。代码看起来像这样:
NSString *stringToSearch = theStringThatYouWantToSearch;
NSString *preMatchString = @"firmware: ";
NSString *terminatingCharacter = " ";
NSString *result = [[NSString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:stringToSearch];
[scanner scanUpToString:preMatchString intoString:NULL];
[scanner scanString:preMatchString intoString:NULL];
[scanner scanUpToString:terminatingCharacter intoString:&result];
最后,result
应该是“firmware:”之后但在下一个尾随空格(“”)之前的字符串。