当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Replace token's text in ANTLR

问题描述:

I'm trying to replace some token's text from my input program to a specific formated text. I'm using C# as output language.

Example of input:

time#1m2s

My lex grammar for that input:

fragment

DIGIT : '0'..'9'

;

CTE_DURATION

: ('T'|'t'|'TIME'|'time') '#' '-'? (DIGIT ('d'|'h'|'m'|'s'|'ms') '_'?)+

;

Output token text I'd like to get from input example:

0.0:1:2.0

That's means: 0 days, 0 hours, 1 minute, 2 seconds and 0 milliseconds.

Any advice? Thank you in advance.

网友答案:

Here's a way to do that (it's in Java, but shouldn't be hard to port to C#):

grammar Test;

parse
 : CTE_DURATION EOF
 ;

CTE_DURATION 
 : ('T' 'IME'? | 't' 'ime'?) '#' minus='-'?
   (d=DIGITS 'd')? (h=DIGITS 'h')? (m=DIGITS 'm')? (s=DIGITS 's')? (ms=DIGITS 'ms')?
   {
     int days = $d == null ? 0 : Integer.valueOf($d.text);
     int hours = $h == null ? 0 : Integer.valueOf($h.text);
     int minutes = $m == null ? 0 : Integer.valueOf($m.text);
     int seconds = $s == null ? 0 : Integer.valueOf($s.text);
     int mseconds = $ms == null ? 0 : Integer.valueOf($ms.text);
     setText(($minus == null ? "" : "-") + days + "." + hours + ":" + minutes + ":" + seconds + "." + mseconds);
   }
 ;

fragment DIGITS : '0'..'9'+;

Parsing the input time#1m2s results in the following parse tree:

Note that the grammar now accepts time# as well (causing it to produce 0.0:0:0.0), but you can easily produce an exception from the lexer rule in case such input is invalid.

分享给朋友:
您可能感兴趣的文章:
随机阅读: