简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM