在linux下,如何在C语言中使用正则表达式
2016-02-23 09:36
489 查看
使用POSIX函数库中的Regex系列函数来说明在Linux c下如何使用正则表达式
#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
#include <stdlib.h>
#include <string.h>
#define ERRBUF 128
static char * substr(const char * str, unsigned start, unsigned end);
int main(int argc, char *argv[])
{
regex_t myreg;
char err[ERRBUF];
int resulta,resultb;
regmatch_t match[4];
size_t nmatch = 4;
char pattern[] = "[0-9]{3}";
resulta = regcomp(&myreg, pattern, REG_EXTENDED | REG_NEWLINE);
if(resulta != 0)
{
fprintf(stderr, "pattern compiled error\n");
regerror(resulta, &myreg, err, sizeof(err));
regfree(&myreg);
exit(1);
}
char mystring[] = "192.168.121.112";
resultb = regexec(&myreg, mystring, nmatch, match, 0);
if(resultb != 0)
{
regerror(resultb, &myreg, err, sizeof(err));
regfree(&myreg);
exit(1);
}
int x;
for(x = 0; x < nmatch && match[x].rm_so != -1; x++)
{
printf("%s\n",substr(mystring, match[x].rm_so, match[x].rm_eo));
}
printf("x = %d\n",x);
regfree(&myreg);
return 0;
}
static char * substr(const char * str, unsigned start, unsigned end)
{
unsigned n = end - start;
static char strbuf[256];
memset(strbuf,'\0',sizeof(strbuf));
strncpy(strbuf, str + start ,n);
strbuf
= '\0';
return strbuf;
}
注意:不支持使用 \d 来匹配数字
#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
#include <stdlib.h>
#include <string.h>
#define ERRBUF 128
static char * substr(const char * str, unsigned start, unsigned end);
int main(int argc, char *argv[])
{
regex_t myreg;
char err[ERRBUF];
int resulta,resultb;
regmatch_t match[4];
size_t nmatch = 4;
char pattern[] = "[0-9]{3}";
resulta = regcomp(&myreg, pattern, REG_EXTENDED | REG_NEWLINE);
if(resulta != 0)
{
fprintf(stderr, "pattern compiled error\n");
regerror(resulta, &myreg, err, sizeof(err));
regfree(&myreg);
exit(1);
}
char mystring[] = "192.168.121.112";
resultb = regexec(&myreg, mystring, nmatch, match, 0);
if(resultb != 0)
{
regerror(resultb, &myreg, err, sizeof(err));
regfree(&myreg);
exit(1);
}
int x;
for(x = 0; x < nmatch && match[x].rm_so != -1; x++)
{
printf("%s\n",substr(mystring, match[x].rm_so, match[x].rm_eo));
}
printf("x = %d\n",x);
regfree(&myreg);
return 0;
}
static char * substr(const char * str, unsigned start, unsigned end)
{
unsigned n = end - start;
static char strbuf[256];
memset(strbuf,'\0',sizeof(strbuf));
strncpy(strbuf, str + start ,n);
strbuf
= '\0';
return strbuf;
}
注意:不支持使用 \d 来匹配数字
相关文章推荐
- Linux系统性能测试与分析1-整体分析
- Linux笔记(14)——输入输出重定向
- 在没有盗版的世界:Linux 桌面装机量占比可达40%
- linux 日志查询常用命令
- Linux stat函数讲解
- Linux 学习计划书
- Lenovo Y430P安装Linux无线网卡
- linux 给joe jane Julie 发送邮件
- linux之SELinux
- 学习linux计划书 by fanshuyun
- Linux入门常用指令
- Linux驱动第一课--helloworld
- 多线程和fork
- 阿里云服务器(centos6.5)上搭建SVN服务器
- Linux Vi 命令
- Linux 查看进程命令
- Linux下文件的复制、移动与删除
- Linux 系统重启、关机命令
- Linux 软件安装与卸载
- Linux JDK 卸载与设置环境变量