【发布时间】: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)
【问题讨论】:
-
最适合您需求的正则表达式。
-
首先你必须定义你的语法,即对你认为是有效实数的字符串给出严格而详细的定义。如果没有这些信息,我们将无能为力。