【问题标题】:How to use regex c++?如何使用正则表达式 C++?
【发布时间】:2014-02-09 12:09:47
【问题描述】:

我在使用 c++ 正则表达式时遇到了问题。
我有一个像“f 123/123 1234/123/124 12”这样的字符串,我想得到“/”之前的所有数字。

这是我的正则表达式:

“\s(\d+)”。

我在http://rubular.com/ 上试过它,它有效。 这是我的代码:

std::regex rgx("\\s(\\d+)");
std::smatch match;

if (std::regex_search(line, match, rgx))
{
    std::cout << "Match\n";

    std::string *msg = new std::string();
    std::cout << "match[0]:" << match[0] << "\n";
    std::cout << "match[1]:" << match[1] << "\n";
    std::cout << "match[2]:" << match[2] << "\n";

}

但我明白了:

匹配
匹配[0]:123
匹配[1]:123
匹配[2]:

我意识到match[0] 不像 Python 和 Ruby 中的“组”。

【问题讨论】:

    标签: c++ regex search match


    【解决方案1】:

    regex_search 匹配一次(匹配正则表达式的第一个子字符串)。你需要循环。

    尝试以下操作:

    std::regex rgx("\\s(\\d+)");
    std::smatch match;
    
    while (std::regex_search(line, match, rgx))
    {
        std::cout << match[0] << std::endl;
        line = match.suffix().str();
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多