生活随笔
收集整理的這篇文章主要介紹了
re2c使用小结(2)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一次寫的re2c代碼對于處理某些字符串還是不夠智能,不能確保把字符串一次性解析完成。
下面這個寫法用到了condition,確保在正確的狀態下把整個字符串解析正確,即使不正確狀態也會把字符解析出來。
#include <stdio.h>
#include <stdlib.h>/** 定義符號*/
enum{T_EOL = -1,T_DVB,T_NUMBER,T_DOT,T_UNKNOWN,
};/*!types:re2c *//** 掃描*/
enum ScanContition cond = 0;
int scan(char *buf, int *length){
#define YYCTYPE charYYCTYPE * YYCURSOR = buf;YYCTYPE * YYSTART = buf;YYCTYPE * YYMARKER = NULL;YYCTYPE * YYCTXMARKER = NULL;unsigned int ret = 0;if(YYCURSOR==NULL){return T_EOL;} else {
/*!re2c
re2c:yyfill:enable = 0;
re2c:condenumprefix????????????? = EState;
re2c:define:YYCONDTYPE?????????? = ScanContition;
re2c:define:YYSETCONDITION?????? = "cond = #;";
re2c:define:YYSETCONDITION@cond? = #;
re2c:define:YYGETCONDITION?????? = cond;
re2c:define:YYGETCONDITION:naked = 1;
<> :=> DVB
<DVB> "dvb://" => NUM {*length = YYCURSOR - YYSTART;return T_DVB;}
<NUM> [0-9a-fA-F]+ => DOT {*length = YYCURSOR - YYSTART;return T_NUMBER;}
<DOT> [.] => NUM {*length = YYCURSOR - YYSTART;return T_DOT;}
<*> [^\x00] {*length = YYCURSOR - YYSTART;return T_UNKNOWN;}
<*> [\x00] {return T_EOL;}
*/}
}static char buf[] = "dvd:/dvb://888.12.12a/adf";
int yylex(){int token = 0;char *tmp = buf;char *start;int length;token = scan(tmp, &length);while(token!=T_EOL) {printf("token:%d,len:%u,str:%.*s\n",token,length,length,tmp);tmp = tmp+length;length = 0;token = scan(tmp, &length);}return 0;
}int main (int argc,char ** argv){yylex();return 0;
}
編譯的時候加入-c,表示支持condition邏輯。
re2c -ics dvb02.re >dvb02.out.c
運行結果:
可以看到由于condtion的影響,程序在不是正確狀態時,會自動使用默認動作。token:3,len:1,str:d
token:3,len:1,str:v
token:3,len:1,str:d
token:3,len:1,str::
token:3,len:1,str:/
token:0,len:6,str:dvb://
token:1,len:3,str:888
token:2,len:1,str:.
token:1,len:2,str:12
token:2,len:1,str:.
token:1,len:3,str:12a
token:3,len:1,str:/
token:3,len:1,str:a
token:3,len:1,str:d
token:3,len:1,str:f
總結
以上是生活随笔為你收集整理的re2c使用小结(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。