这是一种方法(它在 Java 中,但移植到 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'+;
time#1m2s
在以下解析树中解析输入结果:
请注意,语法现在time#
也接受(导致它产生0.0:0:0.0
),但您可以轻松地从词法分析器规则中产生异常,以防此类输入无效。