分页: 1 / 1

[C++]regex正则匹配

发表于 : 2019年01月30日 16:24
vicyang
1楼索引

Re: [C++]regex正则匹配

发表于 : 2019年01月30日 16:25
vicyang
遍历输出匹配的子元素
//regex_constants - STL pdf P726
#include <iostream>
#include <string>
#include <regex>

using namespace std;
int main(int argc, char *argv[] )
{
string str("foo<1>bar<2>test\nnewline");

smatch m;
bool found;
found = regex_search(str, m, regex("(\\d).*(\\d)", regex_constants::ECMAScript) );
if (found)
for (auto x:m) std::cout << x << endl;

cout << endl;
found = regex_search(str, m, regex("(\\w+)<\\d>(\\w+)", regex_constants::ECMAScript) );
if (found)
for (auto x:m) std::cout << x << endl;
return 0;
}
m[0] 类似 perl 中的 $&
m[1] m[2] 类似 perl 中的 $1 $2

代码: 全选

1>bar<2
1
2

foo<1>bar
foo
bar