Extract numbers from a filename using std::regex_replace

Flaviu_ 1,031 Reputation points
2024-03-03T10:05:26.88+00:00

I have:

	std::string filename{"my_file01010_asset_103.csv"};
	try
	{
		std::cout << std::regex_replace(filename,
			std::regex("[^0-9+]"), "") << std::endl;
	}
	catch (std::exception& ex)
	{
		std::cerr << ex.what();
	}

How can I extract 103 only?

Developer technologies C++
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2024-03-03T10:20:42.0233333+00:00

    For example:

    std::string filename{ "my_file01010_asset_103.csv" };
    std::regex re( R"((\d+)\.)" );
    
    std::smatch m;
    if( std::regex_search( filename, m, re ) )
    {
        std::string number = m[1].str( );
    
        std::cout << number << std::endl;
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.