0

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; }
rici
  • 234,347
  • 28
  • 237
  • 341
sippycup
  • 145
  • 3
  • 12

1 Answers1

0

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.

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
  • Is it possible to ignore 0xa98h altogether and bypass the default rule you mentioned because I would rather have 0xa98 not appear in my results. – sippycup Mar 04 '17 at 05:47
  • To bypass the default rule, you can write one yourself: Use this as the very last rule in the middle part: `. { /* ignore everything else */ }`. – Scheff's Cat Mar 04 '17 at 06:03
  • About ignoring the matched hex number: What you do with the matched pattern is on your own. Modify the sample code, remove `<< yytext` and watch what happens. – Scheff's Cat Mar 04 '17 at 06:05