1
我剛開始學習如何使用regex
進行字符串處理(C++11
新功能)。如果下面的問題太愚蠢,請原諒我。使用regex_search獲取所有匹配的索引?
目前我採用下面的代碼獲得所有比賽的指數:
string str = "aaabxxxaab";
regex rx("ab");
vector<int> index_matches; // results saved here (should be {2, 8})
int track = 0;
smatch sm;
while (regex_search(str, sm, rx))
{
index_matches.push_back(track+sm.position());
string tmp = sm.suffix().str();
track += str.length() - tmp.length(); // update base index
str = tmp;
}
它的工作原理確定,但我每次都手動更新track
(基指數),使其正常工作。
與此同時,我注意到已經有smatch::size()
和smatch::position()
,我想結合使用來實現目標。以下是我想將它們組合在一起但不能工作的代碼(即總是隻能得到{2}
)。
string str = "aaabxxxaab";
regex rx("ab");
vector<int> index_matches; // results saved here
// (should be {2, 8}, but always get only {2})
smatch sm;
regex_search(str, sm, rx);
for (int i=0; i<sm.size(); i++)
index_matches.push_back(sm.position(i));
誰能告訴我如何正確使用smatch::size()
和smatch::position()
得到所有匹配的指標?
有任何引用/你建議我開始學習'regex'的書嗎? – herohuyongtao
@herohuyongtao [cppreference](http://en.cppreference.com/w/cpp/regex)有一個體面的博覽會,如果你問具體關於C++的'' –
Cubbi
謝謝。我會研究它。 – herohuyongtao