0

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.

kitsuneFox
  • 1,243
  • 3
  • 18
  • 31
  • Your language is a bit confusing, `01.23` will match two tokens `0` and `1.23`. Similarly `1.23.45` will also match `1.23` and `.45` – rds Apr 12 '15 at 18:04

1 Answers1

1

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
rds
  • 26,253
  • 19
  • 107
  • 134
  • You can also use `\.`. You have another mistake: your grammar doesn't handle space or line breaks. That's you think it fails. – rds Apr 12 '15 at 18:07