ParseKit 的冒险仍在继续……我的下一个障碍是尝试识别换行符。
这是我的语法:
@symbolState = '\n';
@start = textline*;
textline = Any* eol;
eol = '\n';
这是我的测试文本:
1
2
3
4
5
正在从具有 Unix 格式 (LF) 行尾的 UTF-8 文本文件中读取文本。我已经在 Xcode(文件检查器 -> 文本设置)以及外部使用 TextWrangler 验证了该格式。
这是相关的代码:
#import "FileImporterThing.h"
#import <ParseKit/ParseKit.h>
@interface FileImporterThing ()
@property (nonatomic, retain)PKParser* parser;
- (void)parser:(PKParser *)p didMatchTextline:(PKAssembly *)a;
- (void)parser:(PKParser *)p didMatchEol:(PKAssembly *)a;
@end
@implementation FileImporterThing
@synthesize parser = _parser;
-(id)init
{
if (!(self = [super init])) return nil;
// Have also tried "textline = Any* '\n';"
NSString *g = @"@symbolState = '\n'; @start = textline*; textline = Any* eol; eol = '\n';";
self.parser = [[PKParserFactory factory] parserFromGrammar:g assembler:self];
return self;
}
- (void)testParse
{
// read string from UTF-8 file Unix (LF) line endings
// (this verified in project->file inspector->Text Settings and externally with TextWrangler)
NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"LF-test" ofType:@"parsetext"];
/* file contains text:
1
2
3
4
5
*/
NSString *s = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[self.parser parse:s];
}
- (void)parser:(PKParser *)p didMatchEol:(PKAssembly *)a
{
NSLog(@"eol found");// stack = %@", [a stack]);
}
- (void)parser:(PKParser *)p didMatchTextline:(PKAssembly *)a
{
NSLog(@"textline matched");
}
@end
但恐怕油漆还没干!已经尝试了上述各种变化。我一辈子都无法让解析器识别换行符。我可能可以通过逐行读取文件缓冲区来解决这个问题(无论如何这可能会更高性能?),但仍然可以选择匹配'\ n'。