lex解析器无法正确显示十六进制 [英] lex parser not displaying hex correctly

查看:121
本文介绍了lex解析器无法正确显示十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从已解析的文本文件中识别一个十六进制数字,并且所有内容的准确率均约为99%,但是对于该特定实例0xa98h仍然存在问题.每当发现此行时,它将输出0xa98而不是完全忽略它,因为它无效.我已经尝试过对这种代码进行多种变体,但还没有找到一种方法来排除该问题.

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; }

推荐答案

十六进制数字的模式不考虑数字'a'...'f'.试试这个:

The pattern for hex numbers does not consider digits 'a' ... 'f'. Try this:

[-]?[0][xX][0-9a-fA-F]+ {cout << yytext << " Number" << endl; }

更多观察结果:

  1. [x|X]中的竖线可能是错误的.否则,这也将起作用:0|a98h.
  2. 样本末尾的"h"不匹配. (这可能会或可能不会.)
  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.)

另一种方法可能是这样(test-hex.l):

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; }

在cygwin上使用flex和gcc进行了编译和测试:

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

没有匹配的模式h.之所以打印出来,是因为lex/flex会生成一个默认规则,以回显与标准输出不匹配的所有内容.

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.

这篇关于lex解析器无法正确显示十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆