博客日历
2025年09月 | ||||||
一 | 二 | 三 | 四 | 五 | 六 | 七 |
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 1 | 2 | 3 | 4 | 5 |
存档
2025年03月 2024年
03月 04月 05月 2021年
01月 02月 11月 12月 2020年
02月 03月 04月 05月 06月 07月
09月 2018年
09月 2017年
01月 02月 07月 2016年
01月 04月 07月 08月 11月 12月
2015年
01月 02月 03月 05月 09月 10月
11月 2014年
01月 02月 03月 04月 05月 06月
07月 08月 09月 10月 11月 12月
2013年
01月 02月 03月 04月 05月 06月
07月 08月 09月 10月 11月 12月
2012年
01月 02月 03月 04月 05月 06月
07月 08月 09月 10月 11月 12月
2011年
01月 02月 03月 04月 05月 06月
07月 08月 09月 10月 11月 12月
2010年
01月 02月 03月 04月 05月 06月
07月 08月 09月 10月 11月 12月
2009年
03月 04月 05月 06月 07月 08月
09月 10月 11月 12月
在C/C++中使用POSIX/Linux正则表达式
//rm test.exe;gcc -o test.exe test.cpp;./test.exe
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
void show_return_code_message(regex_t *reg,int ret,const char* func)
{
size_t length=regerror(ret, reg,NULL, 0);
char *err_msg=new char[length];
regerror(ret, reg,err_msg,length);
fprintf(stderr,"%s return: ret=%d, %s\n", func, ret,err_msg);
delete [] err_msg;
}
void match(char* str,char* pattern)
{
char *tmp_str= str;
regex_t reg;
memset(®, 0,sizeof(regex_t));
//编译正则表达式
int ret=regcomp(®, pattern,REG_NEWLINE|REG_EXTENDED);
if (0 ==ret)
{
bool matche_next=true;
while (matche_next)
{
//regmatch[0]是整个正则表达式的匹配结果
//regmatch[1...reg.re_nsub]是各个子正则表达式的匹配结果
regmatch_t*regmatch=new regmatch_t[reg.re_nsub
*sizeof(regmatch_t)];
int status=regexec(®,tmp_str, 1,regmatch, 0);
matche_next= (0 ==status);
if (0 ==status)
{
//rm_so存放匹配文本串在目标字符串tmp_str中的开始位置
int start=regmatch[0].rm_so;
//rm_eo 存放结束位置
int end=regmatch[0].rm_eo;
int matched_length=end-start;
char *matched=new char[matched_length+ 1];
strncpy(matched,tmp_str+start,matched_length);
matched[matched_length] ='\0';
printf("%s\n",matched);
delete [] matched;
//剩下的字符串将再次进行匹配测试
tmp_str=tmp_str+start+matched_length;
}
else
{
show_return_code_message(®,status,"regexec()");
}
delete[] regmatch;
} // end while
regfree(®);
}
else
{
show_return_code_message(®,ret,"regcomp()");
}
}
int main()
{
char *str="xxxxCDCHNCT02389.KORKF.gzzhangsanCDYHNUG78690.ABCDE.gzkkk";
char *pattern="(CD|SD|TD)[A-Z0-9]{5}[0-9]{5}\\.[A-Z0-9]{5}";
match(str,pattern);
//输出:
//CDCHNCT02389.KORKF
//CDYHNUG78690.ABCDE
return 0;
}
备注:
Cygwin+Eclipse CDT调试配置
1.添加D:\cygwin\bin到系统的PATH变量,可以使 Eclipse 识别出Cygwin GCC
2.首选项 -> C/C++ -> 调试 -> Source Lookup Path -> 路径映射:\cygdrive\d <=> D:\ ,可以解决调试找不到源码的问题。
MinGW+Eclipse CDT调试配置
1.添加D:\MinGW\bin到系统的PATH变量,可以使 Eclipse 识别出MinGW GCC
Cygwin+Eclipse CDT调试配置
1.添加D:\cygwin\bin到系统的PATH变量,可以使 Eclipse 识别出Cygwin GCC
2.首选项 -> C/C++ -> 调试 -> Source Lookup Path -> 路径映射:\cygdrive\d <=> D:\ ,可以解决调试找不到源码的问题。
MinGW+Eclipse CDT调试配置
1.添加D:\MinGW\bin到系统的PATH变量,可以使 Eclipse 识别出MinGW GCC
上一篇: International Phonetic Alphabet(国际音标)
下一篇: 用SQL脚本为SQL 2008添加登录名,数据库用户名及其映射
分类:杂谈随感 查看次数:5898 发布时间:2012/8/8 19:18:51