我想通過解析UVA985中的輸入來嘗試C++ 11 regex
庫,但是,我不明白如何在容器中存儲所有匹配,以便可以遍歷並與它一起工作。如何在C++中正確存儲正則表達式匹配
#include <regex>
#include <string>
#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
vector<string> get_names(const string &sentence) {
vector<string> vname;
regex author_regex("(.+\\.\\,\\s)|(.+\\.:)", regex_constants::ECMAScript);
smatch names; // This is always empty
regex_match(sentence, names, author_regex); // Is this correct?
for (auto name: names) {
vname.push_back(name.str() + ".");
}
return vname;
}
int main(void) {
const string papers[] = {
"Smith, M.N., Martin, G., Erdos, P.: Newtonian forms of prime \
factor matrices",
"Erdos, P., Reisig, W.: Stuttering in petri nets",
"Smith, M.N., Chen, X.: First oder derivates in structured programming",
"Jablonski, T., Hsueh, Z.: Selfstabilizing data structures" };
vector<vector<string>> input_data;
for (auto paper : papers) {
input_data.push_back(get_names(paper));
}
int counter = 1;
for (auto scenario : input_data) {
cout << "Paper " << counter << ":\n";
for (auto author: scenario) {
cout << author << endl;
counter += 1;
}
}
return 0;
}
我試圖改變正則表達式模式爲爲.
簡單的事,但容器smatch
總是空的,我失去了什麼?
'regex_match'只有在表達式匹配完整的輸入字符串時纔會成功。你的不是。您可能正在尋找'regex_search' –
@IgorTandetnik謝謝,如果您將它寫爲答案,我會高興地接受。 –