正则程序库(regex)

「正则表达式」就是一套表示规则的式子,专门用来处理各种复杂的操作。

std::regex是C++用来表示「正则表达式」(regular expression)的库,于C++11加入,它是class std::basic_regex<>针对char类型的一个特化,还有一个针对wchar_t类型的特化为std::wregex。

正则文法(regex syntaxes)

std::regex默认使用是ECMAScript文法,这种文法比较好用,且威力强大,常用符号的意义如下:

符号 意义
^ 匹配行的开头
$ 匹配行的结尾
. 匹配任意单个字符
[…] 匹配[]中的任意一个字符
(…) 设定分组
\ 转义字符
\d 匹配数字[0-9]
\D \d 取反
\w 匹配字母[a-z],数字,下划线
\W \w 取反
\s 匹配空格
\S \s 取反
+ 前面的元素重复1次或多次
* 前面的元素重复任意次
? 前面的元素重复0次或1次
{n} 前面的元素重复n次
{n,} 前面的元素重复至少n次
{n,m} 前面的元素重复至少n次,至多m次
| 逻辑或

上面列出的这些都是非常常用的符号,靠这些便足以解决绝大多数问题了。

匹配(Match)

 

 

#include<iostream>
#include<regex>//正则表达式

using namespace std;
#include<vector>
vector<string> v;

void re_math(string text, string re_text)
{
	v.clear();
	std::regex reg(re_text);
	std::string content(text);
	std::smatch m;
	auto pos = content.cbegin();
	auto end = content.cend();
	for (; std::regex_search(pos, end, m, reg); pos = m.suffix().first)
	{
		cout << m.str(0) << endl;
		v.push_back(m.str(0));
	}
	
}

int main()
{
   re_math("127.0.0.1:21503 device", ".*?:\\d+.*?device");
}

匹配结果c1234567de

linux运行

g++ hello.cpp -o hello

运行 

./hello

编译和运行一起执行 

g++ hello.cpp -o hello && ./hello