1 正则表达式标准库
C++11 正式将正则表达式的的处理方法纳入标准库,从语言级上提供了标准的支持。常用方法如下:
- std::regex: (本质是 std::basic_regex),初始化正则对象
- std::regex_match(fname , txt_regex): 匹配字符串和正则表达式。匹配成功时,会返回 true,否则返回 false。
- std::regex_match(fname , base_match , base_regex):匹配并返回匹配到的结果到第二个参数。
例子example_13 code:
#include <iostream>#include <string>#include <regex>using namespace std;int main(){string files[]={"foo.txt", "bar.txt", "test", "a0.txt", "AAA.txt"};//生成正则对象regex txt_regex("[a-z]+\\.txt");//仅查询for (const auto &file : files){cout<<file<<": "<<regex_match(file, txt_regex)<<endl;}smatch matches;for (const auto &file : files){if (regex_match(file, matches, txt_regex)){//smatch第一个元素为整个字符串cout<<"whole string: "<<matches[0].str()<<endl;cout<<"match: "<<matches[1].str()<<endl;}}}
2 Linux平台原始正则表达式
在Linux平台上,有一个regex.h提供了原始的C语言的正则表达式支持,主要有以下几个函数:
- int regcomp(regex_t _preg, const char _regex, int cflags);
- int regexec(const regex_t _preg, const char _string, size_t nmatch, regmatch_t pmatch[], int eflags);
- size_t regerror(int errcode, const regex_t _preg, char _errbuf, size_t errbuf_size);
- void regfree(regex_t *preg);
regmatch_t数组用来存储匹配的结果,该参数为数组的原因实际上是为了匹配group,其规则和Java等实现一致,若匹配成功,数组的[0]为整个匹配串,即group(0),其他为各个匹配到的组。匹配失败则rm_eo-rm_so=0。
//rm_so为匹配字符串起始偏移(start offset),rm_eo为匹配字符串的终止偏移(end offset)。typedef struct {regoff_t rm_so;regoff_t rm_eo;} regmatch_t;
代码示例如下:
#include <stdio.h>#include <regex.h>#include <string.h>int main(void){const char *str = "itf:e1;crc4:enabled;xxx";const char *pattern = "^itf:(e1|t1)?(;(crc4):([0-9a-zA-Z_]*))?(;(t1fm):([0-9a-zA-Z_]*))?(;(t1tx):([0-9a-zA-Z_]*))?(;(t1rx):([0-9a-zA-Z_]*))?(;(.*))?$";regex_t reg;regmatch_t match[16];int ret = 0;ret = regcomp(®, pattern, REG_EXTENDED | REG_NEWLINE);if(ret != 0)printf("error\n");else{ret = regexec(®, str, 16, match, 0);if(ret != REG_NOMATCH){char buf[1024] = {0};for (int i=1;i<=15;i++){memset(buf, 0, 1024);int len = match[i].rm_eo - match[i].rm_so;memcpy(buf, str + match[i].rm_so, len);printf("get buf: %s\n", buf);}}else{printf("match nothing\n");}}regfree(®);return 0;}
