本文介紹了如何使用 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
()
inregex
to 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 匹配多個結果的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!