如何在特定字符序列之后的一行中获取一个数字,这些字符的分隔符数量可能会有所不同?

How to get a number in a line after a certain sequence of characters which can vary in number of delimeters?

我正在逐行读取输入的 txt 文件并尝试获取特定行并从中提取数字。该行可能如下所示:

"; Max: 144"
";  Max: 28292"
";   Max: 283829"
";Max: 12"

所以基本上它可以在“Max:”之前有任意数量的分隔符。我正在尝试使用 line.find(...);它告诉我给定的序列是否在行中,然后使用 line.erase(...) 从中删除不需要的字符串,但我必须检查每一种可能性,所以它没有很好地编程并且容易出错.它看起来像这样:

size_t pos = line.find("; Max: ");
size_t pos1 = line.find(";  Max: ");
size_t pos2 = line.find(";   Max: ");
if (pos != -1)
     {
         std::string x = "; Max: ";
         size_t l = x.length();
         procs = std::stoi(line.erase(pos, l));
     }else if(pos1 != -1){
         std::string z = ";  Max: ";
         size_t l = z.length();
         procs = std::stoi(line.erase(pos1, l));
     }else if(pos2 != -1){
         std::string o = ";   Max: ";
         size_t l = o.length();
         procs = std::stoi(line.erase(pos2, l));
     }
...

我也曾尝试使用正则表达式,但它使我的程序减慢了大约 8 倍,这是非常不受欢迎的。如何快速正确的提取号码?

有一个智能解决方案。使用 find_first_of 检测第一个数字,然后提取该行的其余部分。

auto found = line.find_first_of("123456789");
if (found != std::string::npos)
{
    procs = std::stoi(line.substr(found));
}

假设该行中没有其他数字。