c++ - std::regex 不匹配
问题描述
我有一个regex101可以正常工作的正则表达式:
正如预期的那样,有 2 场比赛。
现在我想用 std 的regex_token_iterator拆分相同的内容:
const std::string text = "This is a test string [more or less] and here is [another].";
const std::regex ws_re("\(?<=\[)(.*?)(?=\])\gm"); // HOW TO WRITE THE ABOVE REGEX IN HERE?
std::copy( std::sregex_token_iterator(text.begin(), text.end(), ws_re, -1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(std::cout, "\n"));
这编译得很好,但没有任何东西打印到标准输出。
我认为正则表达式必须以其他方式编写,您能指出我的错误吗?
解决方案
您可以使用
const std::regex ws_re(R"(\[([^\]\[]*)\])");
此外,请确保通过将1
作为最后一个参数传递给std::sregex_token_iterator
而不是-1
(-1
在拆分时使用)来提取第 1 组值。
R"(\[([^\]\[]*)\])"
是定义\[([^\]\[]*)\]
正则表达式模式的原始字符串文字。它匹配
\[
- 一个[
字符([^\]\[]*)
[
- 第 1 组:除and之外的任何零个或多个字符]
\]
- 一个]
字符。
请参阅C++ 演示:
#include <string>
#include <iostream>
#include <regex>
using namespace std;
int main() {
const std::string text = "This is a test string [more or less] and here is [another].";
const std::regex ws_re(R"(\[([^\]\[]*)\])");
std::copy( std::sregex_token_iterator(text.begin(), text.end(), ws_re, 1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
推荐阅读
- php - 如何每 10 分钟错开一次循环
- php - 正则表达式匹配相同的单词
- http - http.Client 在编译为 wasm 的 Go 中不起作用
- php - phpmyadmin登录页面加载一半
- ruby - rbenv — 'find_spec_for_exe': 找不到带有可执行包 (Gem::GemNotFoundException) 的 gem bundler (>= 0.a)
- r - 将非表格形式的文本保存为 tsv 文件
- c# - log4net 可以生成一个逗号分隔的有效 Json 文件吗
- android - Android 4.4 上 AnimatorSet.start 中的 NullPointerException
- java - 花费大量时间打开工作簿
- angular - Angular bypassSecurityTrustResourceUrl 说任何参数都是未定义的