问题
I'm trying to identify a hex number from a parsed text file and everything is about 99% accurate however I keep having an issue with this certain instance 0xa98h. whenever it finds this line it will output 0xa98 instead of ignoring it altogether since it is not valid. I've tried so many variations to this code and have yet to find a way to exclude that issue.
[-]?[0][x|X][0-9A-F]+ {cout << yytext << " Number" << endl; }
回答1:
The pattern for hex numbers does not consider digits 'a' ... 'f'. Try this:
[-]?[0][xX][0-9a-fA-F]+ {cout << yytext << " Number" << endl; }
Further observations:
- The vertical bar in
[x|X]
is probably wrong. Otherwise, this would also work:0|a98h
. - The 'h' at end of sample is not matched. (This may or may not be intended.)
An alternative approach could be this (test-hex.l
):
%{
#include <iostream>
using namespace std;
%}
%option caseless
%%
[-]?[0][x][0-9a-f]+ {cout << yytext << " Number" << endl; }
%%
int main(int argc, char **argv) { return yylex(); }
int yywrap() { return 1; }
Compiled and tested with flex and gcc on cygwin:
$ flex -V
flex 2.6.3
$ flex -otest-hex.cc test-hex.l ; g++ -o test-hex test-hex.cc
$ echo '0xa98h' | ./test-hex
0xa98 Number
h
There is no pattern matching h
. This is printed because lex/flex generate a default rule to echo everything what is not matched to standard output.
来源:https://stackoverflow.com/questions/42592185/lex-parser-not-displaying-hex-correctly