美文网首页
c++正则表达式库re2示例

c++正则表达式库re2示例

作者: 一路向后 | 来源:发表于2022-02-13 20:56 被阅读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

相关文章

  • c++正则表达式库re2示例

    1.源码实现 2.编译源码 3.运行及其结果

  • 正则表达式

    菜鸟教程正则表达式教程RE2正则表达式(golang执行的是RE2标准的正则表达式)go语言中单行模式的用法可以查...

  • C++ re2的linux配置

    Windows上配置不成功,不要白费力气了 Linux配置C++ re2步骤: 1.首先下载c++ RE2安装包 ...

  • pyre2 安装使用

    re2 和 pyre2 re2是google提供的快速、安全 的正则表达式引擎pyre2是提供给python的第三...

  • Golang标准库——regexp

    regexp regexp包实现了正则表达式搜索。正则表达式采用RE2语法(除了\c、\C),和Perl、Pyth...

  • Python正则表达式指南

    本文介绍了Python对于正则表达式的支持,包括正则表达式基础以及Python正则表达式标准库的完整介绍及使用示例...

  • boost::regex库进行正则表达式替换

    C++的boost::regex库提供了3种正则表达式匹配类型。perlposix::basicposix::ex...

  • DB2教程

    词Java示例搜索字符串中的特定单词Java示例拆分正则表达式JJava示例拆分正则表达式Java示例替换首次出现...

  • 使用boost::regex库进行正则表达式匹配

    代码非常简单,但是C++的regex库功能非常全面,提供了perl格式正则表达式,posix extend正则表达...

  • C++调用lua方式

    目标 使用C++调用lua接口 示例 lua代码(test.lua) C++调用示例(lua_test.cpp) ...

网友评论

      本文标题:c++正则表达式库re2示例

      本文链接:https://www.haomeiwen.com/subject/djdqlrtx.html