C++11 Regex submatches

C++11 Regex submatches

本文关键字:submatches Regex C++11      更新时间:2023-10-16

我有以下代码来提取左&从类型

字符串的正确部分

[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

有人可以给我一些有关如何实现这一目标的建议吗?感谢所有帮助。

您需要在第一个'[','," ->"之后获得所有内容您正在为Multiline评论/*... */,必须排除" */",否则,以至于以下是贪婪的东西,直到最后一个,就像您的情况下发生了一切,>"。您无法真正将DOT用于任何字符,因为它变得非常贪婪。

这对我有用:

\[([^-\]]+)->([0-9]+)\]

'^'在[...]的开头使所有字符都如此,除了' - ',因此您可以避免" ->"answers"]',被接受

您需要的是使其更具体:

[([^]]*)->([^]]*)]

为了避免捕获太多数据。请参阅现场演示。

您可以使用.*?模式而不是[^]]*,但效率较低。