使用flex 做关键词、正则表达式过滤
編寫 .l文件
%{
c 頭文件 和變量定義
%}
?
%%
{pattern} {c action code;}
?
%%
c function definition
?
compile && link
flex -o my.c my.l
gcc -o my my.c -lfl
?
當無main函數時, 需要 -lfl && %option noreject noyywrap
?
?
?
中文支持:
.l 文件與需要檢測的數據文件是同一編碼, 否則識別不出來
?
?
vim securecrt centos 編輯顯示中文:
centos?? 編輯i18n文件, 設置utf8
securecrt 設置成utf8
~/.vimrc: set encoding=utf8??????? &&????????? set termencoding=utf8
?
====================================================================
example:
#!/bin/shcat keyword | gawk 'BEGIN{print "%%";} {#check if need ""if(index($1, "/"") == 0)print "/"" $0 "/" {";elseprint $0 " {";print "/tprintf(/"found: %s, lineno: %d, length: %d//n/"" ", yytext, yylineno, yyleng);";print "/tstrcpy(pat, yytext);";print "/tyyret = 1;";print "/tYY_FLUSH_BUFFER;/*do not resume scan remain buffer. */";print "/treturn 1;/*1 will be returned by yylex *//n}/n/n"; } END{print ".|//n {/* eat up any unmatched. do nothing */}/n/n";print "<<EOF>> {";print "/treturn 0;/n}/n/n" }' > kk && cat head kk tail > k2.l make
?
makefile:
?# Basic Makefile -- provides explicit rules
# Creates "myprogram" from "scan.l" and "myprogram.c"
#
CC = g++
CFLAGS = -g
LDFLAGS = #-lfl, can use this if && only if no main provided,
LEX=flex
check: k2.o check.o
?$(CC) -o $@? $(LDFLAGS) $^
check.o: check.cpp
?$(CC) $(CPPFLAGS) $(CFLAGS) -o $@ -c $^
k2.o: k2.cpp
?$(CC) $(CPPFLAGS) $(CFLAGS) -o $@ -c $^
k2.cpp: k2.l
?$(LEX) $(LFLAGS) -o $@ $^
clean:
?$(RM) *.o k2.cpp
?
?
check.cpp: test code
#include <stdio.h> #include <time.h>extern int check2(FILE *f, char *fn, char *pattern, FILE *out, int *ret, int output);int main(int argc, char *argv[]) {int ret;int yret = 0;clock_t start, end;unsigned int all;unsigned int found = 0, notfound = 0;FILE *out = fopen("/dev/null", "a");char pattern[1024];int i = 0, j = 0;char *prefix = "../../../sample_mail/spam_test/spam.";char path[200];for(i = 1; i < 10001; i++){sprintf(path, "%s%d", prefix, i);FILE * f = fopen(path, "r");if(f != 0){start = clock();for(j = 0; j < 10; j++){fseek(f, 0, SEEK_SET);pattern[0] = 0;ret = check2(f, path, pattern, out, &yret, (int)(j==0));}end = clock();all += end - start;if(ret > 0)found++;elsenotfound++;}else{printf("can not open file: %s/n", path);}fclose(f);}printf("total time: %d, found: %d, notfound; %d/n", all, found, notfound);return 0; }
總結
以上是生活随笔為你收集整理的使用flex 做关键词、正则表达式过滤的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: connect 超时
- 下一篇: 封装libspf