regex样例
Posted ~千里之行,始于足下~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了regex样例相关的知识,希望对你有一定的参考价值。
#include <iostream>
#include <regex>
#include <string>
int main()
std::string input;
std::getline(std::cin, input);
std::regex pattern("\\\\d+");
std::smatch match;
std::string output = input;
while (std::regex_search(output, match, pattern))
//只会处理第一个匹配的字符串
std::string number_str = match.str();
int number = std::stoi(number_str);
int square = number * number;
// 自定义处理
square = square + 1;
output.replace(match.position(), match.length(), std::to_string(square));
std::cout << output << std::endl;
return 0;
//hyperscan的测试样例
#include <hs/hs.h>
#include <iostream>
int main()
hs_database_t* db;
hs_compile_error_t* compile_err;
hs_error_t err;
// 定义正则表达式模式
const char* regex = "hello|world";
// 编译正则表达式为Hyperscan数据库
err = hs_compile(regex, HS_FLAG_CASELESS, HS_MODE_BLOCK, NULL, &db, &compile_err);
if (err != HS_SUCCESS)
std::cerr << "ERROR: Unable to compile regex: " << compile_err->message << std::endl;
hs_free_compile_error(compile_err);
return 1;
// 定义要匹配的输入
const char* input = "Hello, world!";
// 定义回调函数,当匹配到正则表达式时调用
auto onMatch = [](unsigned int id, unsigned long long from, unsigned long long to, unsigned int flags, void* ctx) -> int
std::cout << "Match found at position " << from << " to " << to << std::endl;
return 0;
;
// 使用Hyperscan执行正则表达式匹配
hs_scratch_t* scratch = nullptr;
err = hs_alloc_scratch(db, &scratch);
if (err != HS_SUCCESS)
std::cerr << "ERROR: Unable to allocate scratch space: " << err << std::endl;
hs_free_database(db);
return 1;
err = hs_scan(db, input, strlen(input), 0, scratch, onMatch, nullptr);
if (err != HS_SUCCESS)
std::cerr << "ERROR: Unable to scan input: " << err << std::endl;
hs_free_scratch(scratch);
hs_free_database(db);
return 1;
// 释放Hyperscan资源
hs_free_scratch(scratch);
hs_free_database(db);
return 0;
//Match found at position 0 to 5
//Match found at position 7 to 11
vector<string> findallstr()
vector<string> vstrs;
string str = "Hello999 obc888kadkfj777dkfja666";
std::regex re("\\\\d+");
std::cregex_iterator it(str.c_str(), str.c_str()+str.size(), re);
std::cregex_iterator end;
for (; it != end; ++it)
cout << it->str() << endl;
vstrs.push_back(it->str());
return vstrs;
以上是关于regex样例的主要内容,如果未能解决你的问题,请参考以下文章
C++ 中三种正则表达式比较(C regex,C ++regex,boost regex)
MSVC下使用gnu regex(正则表达式C语言接口regex.h)
Regex在C#中如何在javascript中获得类似于regex.exec的结果?