How to match multiple results using std::regex(如何使用 std::regex 匹配多个结果)
问题描述
例如.如果我有一个像first second third Fifth"这样的字符串,并且我想在一个操作中匹配每个单词以一个一个地输出它们.
for example.If I have a string like"first second third forth"and I want to match each single word in one operation to output'em one by one.
我只是认为(S*){0,}"会起作用.但实际上并没有.
我该怎么办?
这是我的代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
regex exp("(\b\S*\b)");
smatch res;
string str = "first second third forth";
regex_search(str, res, exp);
cout << res[0] <<" "<<res[1]<<" "<<res[2]<<" "<<res[3]<< endl;
}
我期待着您的帮助.:)
I'm looking forward to your kindly help. :)
推荐答案
这可以在C++11的regex中完成.
This can be done in regex of C++11.
两种方法:
- 您可以在
regex中使用()来定义您的捕获.
- You can use
()inregexto define your captures.
像这样:
string var = "first second third forth";
const regex r("(.*) (.*) (.*) (.*)");
smatch sm;
if (regex_search(var, sm, r)) {
for (int i=1; i<sm.size(); i++) {
cout << sm[i] << endl;
}
}
现场观看:http://coliru.stacked-crooked.com/a/e1447c4cff9ea3e7
你可以使用
sregex_token_iterator():
string var = "first second third forth";
regex wsaq_re("\s+");
copy( sregex_token_iterator(var.begin(), var.end(), wsaq_re, -1),
sregex_token_iterator(),
ostream_iterator<string>(cout, "
"));
现场观看:http://coliru.stacked-crooked.com/a/677aa6f0bb0612f0
这篇关于如何使用 std::regex 匹配多个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 std::regex 匹配多个结果
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
