VC++6.0本身並不支持正則表達式,需要鏈接一個支持正則表達式的庫。支持正則表達式的庫有boost、GNU、微軟發佈的greta等。這裏使用boost庫。Boost庫是一個經過千錘百煉、可移植、提供源代碼的C++庫,作爲標準庫的後備,是C++標準化進程的發動機之一。 Boost庫由C++標準委員會庫工作組成員發起,其中有些內容有望成爲下一代C++標準庫內容。Boost庫爲我們帶來了最新、最酷、最實用的技術,是不折不扣的“準”標準庫。(參考資料:http://baike.baidu.com/view/663725.htm)接下來將接紹如何在VC++ 6.0中使用Boost庫。
1、下載Boost。
下載地址:http://downloads.sourceforge.net/boost/boost_1_38_0.zip?use_mirror=jaist
下載後解壓保存在目錄D:/boost下。
2、編譯Boost,這裏需要使用Boost的Regex庫,所以只選擇目錄D:/boost/libs/regex/build 下的這部分進行編譯。
編譯方法:在“運行”裏輸入“cmd”,打開命令提示符;輸入命令“cd:/boost/libs/regex/build” 設置當前目錄,把VCVARS32.BAT文件用鼠標拖到打開的cmd窗口("D:/Program Files/Microsoft Visual Studio/VC98/Bin/VCVARS32.BAT"),然後回車。輸入命令“nmake -fvc6.mak”,等待幾分鐘,OK了!,D:/boost/libs/regex/build多了一個vc6的文件夾,裏面是很多lib和dll文件。
3、配置VC6.0,使它編譯使時候能找到正則庫。
把文件夾VC6拷貝到Visual Studio安裝目錄下的VC98,改名爲“BoostRegex”。然後打開vc++6.0,選擇“Tools->Options->Directories->Include files”,加入一行“D:/BOOST”
選擇“Tools->Options->Directories->Library file”,加入一行“C:/PROGRAM FILES/MICROSOFT VISUAL STUDIO/VC98/BOOSTREGEX”(VC的安裝目錄),配置也OK了!
4、編寫程序測試
SDK下的測試:
#include "stdafx.h" #include <cstdlib> #include <stdlib.h> #include <boost/regex.hpp> #include <string> #include <iostream> using namespace std; using namespace boost; regex expression("^select ([a-zA-Z]*) from ([a-zA-Z]*)"); int main(int argc, char* argv[]) { std::string in; cmatch what; cout << "enter test string" << endl; getline(cin,in); if(regex_match(in.c_str(), what, expression)) { for(int i=0;i<what.size();i++) cout<<"str :"<<what.str()<<endl; } else { cout<<"Error Input"<<endl; } return 0; } |
輸出: str:select name from table
str:name
str:table
MFC下的測試(有幾個地方要注意,下面有提示):
新建一個對話框的MFC工程,
加入頭文件 #include <boost/regex.hpp>
在按鈕鼠標單擊事件響應函數中加入
boost::regex expression("^select ([a-zA-Z]*) from ([a-zA-Z]*)"); CString in = "select gm from tab"; CString sRet; boost::cmatch what; if(boost::regex_match(LPCSTR(in), what, expression))//CString轉string { for(int i=0;i<what.size();i++){ sRet = (what.str()).c_str();//string轉CString MessageBox(sRet); } } else { MessageBox("Error Input"); } |
(參考資料:http://dev.yesky.com/491/7549991.shtml)
PS:VC中執行單獨編譯時有時出現錯誤:
fatal error C1083: Cannot open precompiled header file: 'Debug/*.pch': No such file or directory
這時只要全部編譯鏈接一次就可以了。