Asanka Herath
Asanka Herath

Reputation: 1611

C++ find specific number in a string

I'm quite new to regular expressions. I have this string.

string s = media_type=video|key_frame=1|pkt_pts=1516999|pkt_pts_time=50.566633|pkt_dts=1516999|

I need to get 50.566633 value extracted using string operators and regular expressions in C++. Can some one suggest a way to do this?

Upvotes: 0

Views: 261

Answers (1)

Galik
Galik

Reputation: 48605

Regex is well worth studying because it is so useful.

This works for me:

#include <regex>
#include <iostream>

std::string s = "media_type=video|key_frame=1|pkt_pts=1516999|pkt_pts_time=50.566633|pkt_dts=1516999|";

int main()
{
    // parens () define a capture group to extract your value
    // so the important part here is ([^|]*)
    // - capture any number of anything that is not a |
    std::regex rx("pkt_pts_time=([^|]*)");

    std::smatch m;
    if(std::regex_search(s, m, r))
        std::cout << m.str(1); // first captured group
}

Click on Working Example

Upvotes: 2

Related Questions