从字符串中分离子字符串

时间:2018-05-15 15:13:42

标签: c++

我有以下字符串:

std::string str = "Mode:AAA:val:101:id:A1";

我想分隔放在"val:"":id"之间的子字符串。这是我的方法:

std::string pattern1 = "val:";
std::string pattern2 = ":id";
auto pattern1begin = str.find(pattern1);
auto pattern2begin = str.find(pattern2);
auto pattern1end = pattern1begin + pattern1.size();
auto substrlength = pattern2begin - pattern1end;
auto val = str.substr(pattern1end, substrlength);

你知道在上面的例子中可以用来分隔子串的其他一些方法(包括boost或std :: regex)吗?

1 个答案:

答案 0 :(得分:1)

您可能希望找到val:XXX并获取XXX,而不是val::id

之间的内容

如果XXX是一系列数字,那么你可以

#include <iostream>
#include <regex>
#include <string>

int main()
{
    std::string str = "Mode:id:AAA:val:101:id:A1";
    std::smatch matches;
    if (std::regex_search(str, matches, std::regex("val:(\\d+)")))
    {
        std::cout <<  matches[1];
    }
}

演示:https://ideone.com/zFQnDw