【问题标题】:C++ find specific number in a stringC ++在字符串中查找特定数字
【发布时间】:2015-04-18 14:16:27
【问题描述】:

我对正则表达式很陌生。我有这个字符串。

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

我需要在 C++ 中使用字符串运算符和正则表达式提取 50.566633 值。有人可以建议一种方法吗?

【问题讨论】:

标签: c++ regex string


【解决方案1】:

正则表达式非常值得研究,因为它非常有用。

这对我有用:

#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
}

点击Working Example

【讨论】:

  • 非常感谢您的回答。但它说 R 是未定义的。
  • @Asankasanjaya 您必须使用 C++11 才能使正则表达式工作。您是否使用-std=c++11 标志编译? (或 VC++ 等价物)。 (在这种情况下,原始字符串点亮没有帮助,所以我删除了它)
  • 谢谢,我会试试的。
  • 我从您那里得到了代码并进行了一些更改。现在它的工作。这些是我所做的更改。
  • 我更改了行 regex rx("pkt_pts_time=([^|]*)");到正则表达式 r("pkt_pts_time\=([\\+\\-]?(?:\\d*\\.?\\d+))");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 2023-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
相关资源
最近更新 更多