[英]C++11 Regex submatches
我有以下代碼從類型的字符串中提取左右部分
[3-> 1],[2-> 2],[5-> 3]
我的代碼如下所示
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main()
{
regex expr("([[:d:]]+)->([[:d:]]+)");
string input = "[3->1],[2->2],[5->3]";
const std::sregex_token_iterator end;
int submatches[] = { 1, 2 };
string left, right;
for (std::sregex_token_iterator itr(input.begin(), input.end(), expr, submatches); itr != end;)
{
left = ((*itr).str()); ++itr;
right = ((*itr).str()); ++itr;
cout << left << " " << right << endl;
}
}
輸出將是
3 1
2 2
5 3
現在,我嘗試擴展它,以便第一部分將是字符串而不是數字。 例如,輸入將是
[(3),(5),(0,1) - > 2],[(32,2) - > 6],[(27),(61,11) - > 1]
我需要將其拆分為
(3),(5),(0,1) 2
(32,2) 6
(27),(61,11) 1
我嘗試過的基本表達式("(\\\\(.*+)->([[:d:]]+)")
只是將整個字符串分成兩個,如下所示
(3),(5),(0,1)->2],[(32,2)->6],[(27),(61,11) 1
有人可以給我一些建議,以實現這一目標嗎? 感謝所有幫助。
您需要獲取第一個'['之后的所有內容,除了“->”之外,有點像是對多行注釋/ * ... * /做正則表達式,其中必須排除“ * /”,或者否則,正則表達式會變得貪婪並吃掉所有東西,直到最后一個為止,就像您的情況中出現的“->”一樣。 您不能真正將點用於任何字符,因為它非常貪婪。
這對我有用:
\\[([^-\\]]+)->([0-9]+)\\]
[...]開頭的'^'使它成為除'-'以外的所有字符,因此可以避免使用“->”和']'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.