c++正则表达式库re2示例
2022-02-13 本文已影响0人
一路向后
1.源码实现
#include <iostream>
#include <string>
#include <re2/re2.h>
using namespace std;
using namespace re2;
void test1()
{
string regmail = "(\\w+([-+.]\\w+)*)@(\\w+([-.]\\w+)*)\\.(\\w+([-.]\\w+)*)";
RE2 *handle = NULL;
handle = new RE2(regmail, re2::RE2::Quiet);
if(!handle->ok())
{
cout << handle->error() << endl;
return;
}
string content = "test,regular,邮件 test@gmail.com;";
string strval;
if(re2::RE2::Extract(content.c_str(), *handle, "\\0,\\1,\\3,\\5", &strval))
{
cout << strval << endl;
}
if(handle != NULL)
{
delete handle;
handle = NULL;
}
}
void test2()
{
StringPiece group[3];
RE2 re("(\\w+):([0-9]+)");
string content = "please visit localhost:8999 here";
if(re.Match(content, 0, content.size(), RE2::UNANCHORED, group, 3))
{
for(size_t i=0; i<3; i++)
{
cout << group[i] << ";";
}
cout << endl;
}
}
void test3()
{
string host;
int port;
string content = "please visit localhost:8999 here";
RE2::FullMatch("localhost:8999", "(\\w+):([0-9]+)", &host, &port);
cout << host << ";" << port << endl;
RE2 re("(\\w+):([0-9]+)");
RE2::FullMatch("master:8999", re, &host, &port);
cout << host << ";" << port << endl;
}
void test4()
{
RE2 re("(\\w+):([0-9]+)");
string content = "please visit localhost:8999 here";
if(RE2::Replace(&content, re, "127.0.0.1"))
{
cout << content << endl;
}
content = "please visit localhost:8999 here";
RE2::GlobalReplace(&content, re, "127.0.0.1");
cout << content << endl;
}
int main()
{
test1();
test2();
test3();
test4();
return 0;
}
2.编译源码
$ g++ -o test test.cpp -std=c++11 -lre2 -lpthread
3.运行及其结果
$ ./test
test@gmail.com,test,gmail,com
localhost:8999;localhost;8999;
localhost;8999
master;8999
please visit 127.0.0.1 here
please visit 127.0.0.1 here