【问题标题】:How to find real number with regex C++如何使用正则表达式 C++ 查找实数
【发布时间】:2015-08-04 08:13:30
【问题描述】:

我有一个带有实数的字符串。

char buf1[256] = ">m 当前辐照度 [mW/cm2] = 9.1 \r\n"; // 范围 0.0 ~ 999.9

实数范围在 0.0 到 999.9 之间。没有负值。

我编写了如下示例代码。我为此使用了正则表达式。

"\s\d*.\d\s"

无论如何,我现在得到了正确的结果。不过,我也期待下面的网站能有更好的表达。

http://www.regular-expressions.info/floatingpoint.html

为此我尝试了很多方法。例如,

[-+]?([0-9]*.[0-9]+|[0-9]+)

我找不到实数。我只是想知道我的原始表达是否是最好的。

代码片段:

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include <iostream>
#include <vector>
#include <string>
#include <boost\algorithm\string.hpp>
#include <boost/algorithm/string/regex.hpp>

using namespace std;
using namespace boost::algorithm;

TEST_CASE("string parsing", "[STRING]"){

    typedef std::vector<string>::iterator intStr;
    typedef std::vector<double>::iterator dubIter;

    char buf1[256] = ">m Current Irradiance [mW/cm2] = 9.1 \r\n"; // Range 0.0 ~ 999.9
    char buf2[256] = ">m Current Irradiance [mW/cm2] = 90.1 \r\n"; // Range 0.0 ~ 999.9
    char buf3[256] = ">m Current Irradiance [mW/cm2] = 990.1 \r\n"; // Range 0.0 ~ 999.9

    std::vector<string> strVec;
    strVec.push_back(buf1);
    strVec.push_back(buf2);
    strVec.push_back(buf3);

    std::vector<double> dubVec;
    dubVec.push_back(9.1);
    dubVec.push_back(90.1);
    dubVec.push_back(990.1);

    try{
        for (std::pair<intStr, dubIter> i(strVec.begin(), dubVec.begin()); i.first != strVec.end(); ++i.first, ++i.second)
        {
            boost::iterator_range<std::string::iterator> r = find_regex((*i.first), boost::regex{ "\\s\\d*.\\d\\s" });
            std::string ret(r.begin(), r.end());

            {
                CHECK((*i.second) == std::stod(ret));
            }
        }
    }
    catch (const std::invalid_argument& ia){
        std::cerr << "Invalid argument: " << ia.what() << '\n';
    }
}

//$ testAny.exe
//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
//All tests passed(3 assertions in 1 test case)

【问题讨论】:

  • 最适合您需求的正则表达式。
  • 首先你必须定义你的语法,即对你认为是有效实数的字符串给出严格而详细的定义。如果没有这些信息,我们将无能为力。

标签: c++ regex boost


【解决方案1】:

你在网站上看到的那个:

"[+-]?(\\d*\\.\\d+\|\\d+)"

也将匹配单个数字,这可能是也可能不是您想要的。在您的示例中,它们将匹配 cm2 中的 2。如果你真的想只匹配带有小数点的数字,那么只需删除 or 大小写:

"[+-]?\\d*\\.\\d+"

【讨论】:

    【解决方案2】:

    您需要转义“。”在你的正则表达式中。

    "\s\d*.\d\s"
    

    至少应该是:

    "\s\d*\.\d\s"
    

    否则“。”将匹配任何字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多