recognize fractional numbers in JFlex 1.4.3

190 views Asked by At

in my SL.lex file i have this regular expression for fractional numbers:

Digit = [1-9]
Digit0 = 0|{Digit}
Num = {Digit} {Digit0}*
Frac = {Digit0}* {Digit}
Pos = {Num} | '.' {Frac} | 0 '.' {Frac} | {Num} '.' {Frac}
PosOrNeg = -{Pos} | {Pos}

Numbers = 0 | {PosOrNeg}

and then in

/* literals */
{Numbers}            { return new Token(yytext(), sym.NUM, getLineNumber()); }

but every time i try to recognize a number with a dot, it fails and i get an error.

instead of '.' i also tried \\.,\.,".", but every time it fails.

1

There are 1 answers

1
rds On

You are right, . needs to be escaped, otherwise it matches anything but line return.

But quoting characters is done with double quotes, not single quotes.

Pos = {Num} | "." {Frac} | 0 "." {Frac} | {Num} "." {Frac}

If you do that, the input:

123.45

works as expected:

java -cp target/classes/ Yylex src/test/resources/test.txt
line: 1 match: --123.45--
action [29] { return new Yytoken(zzAction, yytext(), yyline+1, 0, 0); }
Text   : 123.45
index : 10
line  : 1
null

Also, regular expressions are more powerful than just unions, you could make it more concise:

Digit = [1-9]
Digit0 = 0 | {Digit}
Num = {Digit} {Digit0}*
Frac = {Digit0}* {Digit}
Pos =  0? "." {Frac} | {Num} ("." {Frac})?
PosOrNeg = -?{Pos}

Number = {PosOrNeg} | 0