使用re2库实现简单的正则表达式匹配
Posted jackie-astro
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用re2库实现简单的正则表达式匹配相关的知识,希望对你有一定的参考价值。
reg_test.cpp内容如下:
#include <vector>
#include <fmt/format.h>
#include <console_color.h>
#include <re2/re2.h>
using namespace re2;
using namespace std;
using namespace fmt;
using namespace concol;
int main(int argc, char **argv)
{
concol::init();
//seperate text and int from a string
int i = 0;
string s("");
if (RE2::FullMatch("My name is Jackie:1234", "([0-9A-Za-z\\s]+):(\\d+)", &s, &i))
cout << s << endl << i << endl;
print_cyan_line();
// find first number in a string
int number = 0;
const char* string_with_two_num = "x*100 + 200";
if (RE2::PartialMatch(string_with_two_num, "(\\d+)", &number))
cout << "first number in "" << string_with_two_num << "" is " << number << endl;
// find second number in a string
if (RE2::PartialMatch(string_with_two_num, "\\d+[^\\d]+(\\d+)", &number))
cout << "second number in "" << string_with_two_num << "" is " << number << endl;
print_cyan_line();
// find all numbers in a string
cout << "All numbers in string "" << string_with_two_num << "" are as follow: " << endl;
StringPiece stringPieceWith2Num(string_with_two_num);
while (RE2::FindAndConsume(&stringPieceWith2Num, "(\\d+)", &number))
cout << number << endl;
print_cyan_line();
// extract int to string when integer overflow causes failure
string digitStr("123456789123456789");
string strInt;
if (!RE2::FullMatch(digitStr, "(\\d+)", &number))
cout << "Parse integer failed" << endl;
if (RE2::FullMatch(digitStr, "(\\d+)", &strInt))
cout << strInt << endl;
print_cyan_line();
// precompile pattern for faster matching, which is faster than sscanf.
vector<string> strings;
strings.push_back("Hello");
strings.push_back("hello");
strings.push_back("heLLo");
strings.push_back("h_e_l_l_o");
strings.push_back("H2 O");
RE2 re("h.*o");
for (auto& x : strings)
if (RE2::FullMatch(x, re))
cout << x << endl;
print_cyan_line();
// case-insensitive match
RE2::Options opts;
opts.set_case_sensitive(false);
RE2 re2("h.*o", opts);
for (auto & x : strings)
if (RE2::FullMatch(x, re2))
cout << x << endl;
print_cyan_line();
// scanning text incrementally
string contents("foo = 3
bar = 5
foobar=foo+bar
jackie = 7
");
StringPiece input(contents);
string var;
int value;
while (RE2::FindAndConsume(&input, "(\\w+) = (\\d+)
", &var, &value))
cout << "var: " << var << ", value: " << value << endl;
print_cyan_line();
// extract all words from a string
StringPiece line("My name is Jackie");
string word;
while (RE2::FindAndConsume(&line, "(\\w+)", &word))
cout << word << endl;
print_cyan_line();
// parse hex/octal/c-radix numbers
int a, b, c, d;
if (RE2::FullMatch("100 40 0100 0x40", "(.*) (.*) (.*) (.*)",
RE2::Octal(&a), RE2::Hex(&b), RE2::CRadix(&c), RE2::CRadix(&d)))
cout << a << ", " << b << ", " << c << ", " << d << endl;
print_cyan_line();
cout << "Press any key to exit..." << endl;
get_char();
return 0;
}
运行结果如下图所示:
以上是关于使用re2库实现简单的正则表达式匹配的主要内容,如果未能解决你的问题,请参考以下文章