由於編譯原理上機實驗中有一道題是關於詞法分析的程序設計,裏面需要用到正則表達式來匹配標示符以及關鍵保留字,但是標準C++庫中沒有正則表達式引擎,網上雖然有其他方法比如大名鼎鼎的boost庫,但是在c++中使用boost的正則表達式引擎則略顯麻煩,畢竟爲了一個很簡單的小程序用上重量級的boost庫有點大材小用了。慶幸的是在網上發現了一個很輕量級,用起來超方便的正則表達式引擎“DEELX 正則引擎”官方網站
http://www.regexlab.com/zh/regref.htm
在裏面可以下載庫(其實也就一個頭文件,沒想到會這麼輕量級吧,嘿嘿),更爲令人興奮地是裏面有中文幫助文檔,並且文檔上對常用正則表達式應用也講的很是詳細,
興奮ing
下面上個demo,匹配代碼中的註釋(僅匹配/* */註釋,如果還想匹配//註釋可以自己擴展)
#include "deelx.h"
#include<stdio.h>
int find_remark(const char * string, int & start, int & end)
{
// declare
static CRegexpT <char> regexp("/\\*((?!\\*/).)*(\\*/)?|//([^\\x0A-\\x0D\\\\]|\\\\.)*");
// find and match
MatchResult result = regexp.Match(string);
// result
if( result.IsMatched() )
{
start = result.GetStart();
end = result.GetEnd ();
return 1;
}
else
{
return 0;
}
}
int main(int argc, char * argv[])
{
char * code1 = "int a; /* a */";
char * code2 = "int a;";
int start, end;
if( find_remark(code1, start, end) )
printf("In code1, found: %.*s\n", end - start, code1 + start);
else
printf("In code1, not found.\n");
if( find_remark(code2, start, end) )
printf("In code2, found: %.*s\n", end - start, code2 + start);
else
printf("In code2, not found.\n");
return 0;
}
說明:
本例中的表達式,考慮了 C 註釋(/*...*/)以及 C++ 註釋(//...)。
但未排出註釋標記位於字符串內部的情況。