如何使用ANTLR解析具有多值字段的CSV文件?

时间:2015-03-19 20:35:15

标签: csv antlr antlr4

我的任务是解析一个CSV文件,该文件在其他公共字段中具有多值字段。该文件如下所示:

AEIO;AEIO;Some random text - lots of possible characters;"Property A: Yes
Property B: XXXXX
Property C: Some value
Property D: 2
Property E: Some text again"
BBBZ;ANOTHERONE;AGAIN - Many possible characters/Like this;"Property A: Yes
Property B: some text
Property AB: more text yet
Property Z: http://someurl.com"
0123;TEXT;More  - long text here;"Property A: Yep
Property M: this value is pretty long!
Property B: Yes
This property has a weird name: and the value has numbers too 2.0
Property Z: ahostname, comma-separated
Property K: anything"

字段值以分号分隔。多值字段包含通过换行符(有时是回车符)彼此分隔的属性 - 值对。多值字段中的属性名称通过冒号与其值分隔。所有字段始终存在,并且始终至少有一个多值属性。

我决定尝试解析这个文件,编写一个ANTLR 4语法。我的作品在下面发布。

file  : row+ ;

row       : identifier FIELD_SEP code FIELD_SEP name FIELD_SEP properties;

identifier: TEXT;
code      : TEXT;
name      : TEXT;

properties     : PROP_DELIM property_and_value (NEWLINE property_and_value)* PROP_DELIM NEWLINE;
property_and_value: TEXT (PROP_VAL_DELIM PROP_VALUE)?;

TEXT          : ~[\r\n";:]+;
PROP_VALUE    : ~[\r\n";]+;
NEWLINE       :  [\r\n]+;
PROP_DELIM    : '"';
FIELD_SEP     : ';';
PROP_VAL_DELIM: ':';

我已经部分成功解析了文件,但是我无法正确读取多值字段中的属性名称和值对。例如,当我尝试阅读上面的示例时,我收到以下错误:

line 1:58 mismatched input 'Property A: Yes' expecting TEXT
line 2:0 mismatched input 'Property B: XXXXX' expecting TEXT
line 3:0 mismatched input 'Property C: Some value' expecting TEXT
line 4:0 mismatched input 'Property D: 2' expecting TEXT
line 5:0 mismatched input 'Property E: Some text again' expecting TEXT
line 6:60 mismatched input 'Property A: Yes' expecting TEXT
line 7:0 mismatched input 'Property B: some text' expecting TEXT
line 8:0 mismatched input 'Property AB: more text yet' expecting TEXT
line 9:0 mismatched input 'Property Z: http://someurl.com' expecting TEXT
line 10:34 mismatched input 'Property A: Yep' expecting TEXT
line 11:0 mismatched input 'Property M: this value is pretty long!' expecting TEXT
line 12:0 mismatched input 'Property B: Yes' expecting TEXT
line 13:0 mismatched input 'This property has a weird name: and the value has numbers too 2.0' expecting TEXT
line 14:0 mismatched input 'Property Z: ahostname, comma-separated' expecting TEXT
line 15:0 mismatched input 'Property K: anything' expecting TEXT

我不确定我在这里做错了什么,所以我请求你的帮助。 如何正确读取此CSV文件?

1 个答案:

答案 0 :(得分:1)

TEXTPROP_VALUE的词法分析规则存在冲突。

一般情况下,ANTLR4会选择较长的匹配,通常PROP_VALUE会为最长的匹配生成令牌(因为它可以匹配文本和:之类的所有内容)在您的示例中AEIO;AEIO;Some random text - lots of possible characters;它不会,因为TEXTPROP_VALUE的匹配长度相同。在这种情况下,第一个RULE确定发出的令牌。

解决此问题:

  • 看看词法分析器规则是分离的(至少对于关键模式而言)
  • 即。删除PROP_VALUE的定义并用(TEXT | PROP_VAL_DELIM)+(或等效的解析器子规则)替换它的出现

e.g。

property_and_value: TEXT (PROP_VAL_DELIM (TEXT | PROP_VAL_DELIM)+)?;

TEXT          : ~[\r\n";:]+;
NEWLINE       :  [\r\n]+;
PROP_DELIM    : '"';
FIELD_SEP     : ';';
PROP_VAL_DELIM: ':';