C++ 正则表达式多浮点

C++ 正则表达式多浮点,c++,regex,boost,C++,Regex,Boost,我已经看了前面的问题,以找到寻找浮点值的最佳方法。我的问题是,我有一行应该包含至少3个浮点值,除了一些其他文本。我想从行中提取前三个浮点值并使用它们。但是,我只能让boost::regex给我第一个值。我做错了什么?我想强制小数的每边至少有一个数字,并且强制小数也必须存在 我的示例输入字符串是 "this is a name" 39.789876 -83.997978 30.000000 我的代码看起来像 std::string line = "\"this is a name\" 39.78

我已经看了前面的问题,以找到寻找浮点值的最佳方法。我的问题是,我有一行应该包含至少3个浮点值,除了一些其他文本。我想从行中提取前三个浮点值并使用它们。但是,我只能让boost::regex给我第一个值。我做错了什么?我想强制小数的每边至少有一个数字,并且强制小数也必须存在

我的示例输入字符串是

"this is a name" 39.789876 -83.997978 30.000000
我的代码看起来像

std::string line = "\"this is a name\" 39.789876 -83.997978 30.000000";
static boost::regex llhNums_regex = boost::regex("[-]?[0-9]+[.][0-9]+");
boost::smatch resultsTwo;
if(boost::regex_search(line, resultsTwo, llhNums_regex))
{
    std::cout << "Found results\n";
}
for(int i = 0 ; i<resultsTwo.size() ; ++i)
{
    std::cerr << i << ": " << resultsTwo[i].str() << std::endl;
}
std::string line=“\”这是一个名称\“39.789876-83.997978 30.000000”;
静态boost::regex llhNums_regex=boost::regex(“[-]?[0-9]+[.][0-9]+”);
boost::smatch results2;
if(boost::regex_search(line,results2,llhNums_regex))
{

我想你用错工具了。如果你想要解析器,就用解析器吧

毕竟,您需要解析数据。实数有许多有效的格式(关于正号、科学符号、NaN和无穷大呢?),您需要的是正确转换的数据,而不是字符串值

您甚至可能想要拥有该名称或可靠地跳过它,即使该名称包含一个数字(OOOPS)

下面是一个使用Boost Spirit的简单方法:

#include <iostream>
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;

bool parse_line(std::string const& line, std::string& name, double& a, double& b, double& c) {
    using It = std::string::const_iterator;
    qi::rule<It, std::string()> quoted = '"' >> *~qi::char_('"') >> '"';

    It f = line.begin(), l = line.end();
    return qi::phrase_parse(f, l, quoted >> qi::double_ >> qi::double_ >> qi::double_, qi::blank, name, a, b, c);
}

int main() {
    std::string name;
    double a, b, c;

    if (parse_line("\"this is a name\" 39.789876 -83.997978 30.000000", name, a, b, c)) {
        std::cout << "Parsed: \n"
            << " Name '" << name << "'\n"
            << " (a,b,c): (" << a << ", " << b << ", " << c << ")\n";
    }
}

对于Regex问题的直接回答:谢谢,这非常有效,我确实认为这比正则表达式好,尽管我不需要担心处理各种形式的浮点数。
Parsed:
 Name 'this is a name'
 (a,b,c): (39.7899, -83.998, 30)