Unix系列平台下有现成的regex库,直接添加即可使用。
windows下可以使用Regex for Windows
相关的函数在regex.h中:
int regcomp (regex_t *compiled,const char *pattern,int cflags) int regexec (regex_t *compiled,char *string,size_t nmatch,regmatch_t matchptr [],int eflags) void regfree (regex_t *compiled) size_t regerror (int errcode,regex_t *compiled,char *buffer,size_t length)
正则表达式需要经过regcomp编译,regexec执行,最后regfree释放资源。
测试代码:
#include <iostream> #include <sys/types.h> #include <stdio.h> #include <cstring> #include <regex.h> using namespace std; #define SUBSLEN 10 #define EBUFLEN 100 #define BUFLEN 1000 int main(int argc,char** argv) { size_t len; regex_t re; regmatch_t subs [SUBSLEN]; char matched [BUFLEN]; char errbuf [EBUFLEN]; int err; char string[] = "!@#$%^&hello world!@#$%^&*()"; char pattern[] = "hello"; printf("String to match: %s\n",string); printf("Match pattern: \"%s\"\n",pattern); err = regcomp(&re,pattern,REG_EXTENDED); if (err) { len = regerror(err,&re,errbuf,sizeof(errbuf)); printf("error: regcomp: %s\n",errbuf); return 1; } err = regexec(&re,string,(size_t) SUBSLEN,subs,0); if (err == REG_NOMATCH) { printf("No match found.\n"); regfree(&re); return 0; } else if (err) { len = regerror(err,sizeof(errbuf)); printf("Error in regexec: %s\n",errbuf); return 1; } printf("Match found.\n"); for (int i = 0; i <= re.re_nsub; i++) { len = subs[i].rm_eo - subs[i].rm_so; if (i == 0) { printf ("Substring begin:%d,len = %d ",(int)subs[i].rm_so,(int)len); } else { printf("subexpression_r_r %d begin: %d,i,(int)len); } memcpy (matched,string + subs[i].rm_so,len); matched[len] = '\0'; printf("Matched substring: %s\n",matched); } regfree(&re); return 0 ; }
Linux下编译:
g++ -c regextest.cpp
g++ -o regextest regextest.o -ldl
执行:
davinciyxw@ubuntu:~/develop/regex_test$ ./regextest
String to match: !@#$%^&hello world!@#$%^&*()
Match pattern: "hello"
Match found.
Substring begin:7,len = 5 Matched substring: hello
---------------------------------------------------------------------------------------------------------
AIX下编译:
xlC -q64 -brtl -o regextest -lpthread regextest.cpp
执行:
[aix][davinciyxw][/Dev/Test]>regextest
String to match: !@#$%^&hello world!@#$%^&*()
Match pattern: "hello"
Match found.
Substring begin:7,len = 5 Matched substring: hello
---------------------------------------------------------------------------------------------------------
Windows下建立C++控制台程序
添加上文中下载的regex.lib到链接器输入,将regex2.dll拷贝至运行目录编译即可。
执行:
略。