lex parser not displaying hex correctly

℡╲_俬逩灬. 提交于 2019-12-12 03:39:56

问题


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:

  1. The vertical bar in [x|X] is probably wrong. Otherwise, this would also work: 0|a98h.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!