ANTLR : How to parse fixed length text file based

2019-07-26 05:01发布

问题:

Input:

101 04200001312345678981107291600A094101US FORD NA             TEST COMPANY101                
5225TEST COMPANY                       11234567898PPDTEST BUYS 110801110801   1098765430000001

Above lines are 94 char fixed length.

Expected output: Based on this input , Antlr grammar should parse based on index positions.

For Example: If parser identify '1' in starting char of line one. It should recognize entire line as a separate string as HEADER1.

Same as if parser finds '5' in starting index of line two. It should recognize entire line as a separate string as HEADER2.

回答1:

fragment Digit: '0'..'9' ;
fragment Alpha: '_' | 'A'..'Z';

Number: Digit+ ;
Alphanumeric: (Letter | Digit)+ ;

header1: '1' Alphanumeric+
header2: '5' Alphanumeric+

WS
  : (' ' | '\t') -> skip //channel (HIDDEN) 
  ;


回答2:

Which tool are you using for parsing?

I get the following tree while parsing with your grammar using Antlr v4 plugin in Android studio.



标签: antlr4