问题
My lex as follows:
LNUM [0-9]+
DNUM([0-9]*"."[0-9]+)|([0-9]+"."[0-9]*)
%%
{LNUM} {
printf("\t");ECHO;printf("\r\n");
}
{DNUM} {
printf("\t");ECHO;printf("\r\n");
}
But it turns out that it can only match numbers like 4.12
.2
,not 42
,45.
etc.(those indented are matched)
Output:
1.
1.
.1
.1
12
12
My target is to match both integers and float numbers.
Can anyone here tell me what's wrong above?
回答1:
Late answer to your question... but for what it's worth, I tried replacing the *
you had in the original lex file (the second pattern for DNUM
) with a +
(because that ensures that you at least have one digit to the right of the decimal point in order for the number to be counted as a decimal...) and it seems to work for me, at least. Hope this helps someone in the future.
lex file:
%{
#include <iostream>
using namespace std;
%}
LNUM [0-9]+
DNUM ([0-9]*"."[0-9]+)|([0-9]+"."[0-9]+)
%option noyywrap
%%
{LNUM}* { cout << "lnum: " << yytext << endl; }
{DNUM}* { cout << "dnum: " << yytext << endl; }
%%
int main(int argc, char ** argv)
{
yylex();
return 0;
}
example input (on command line):
$ echo "4.12 .2 42 45. " | ./lexer
dnum: 4.12
dnum: .2
lnum: 42
lnum: 45.
来源:https://stackoverflow.com/questions/6971581/have-problem-with-lex