【问题标题】:Regular Expression Multiple Floating Point正则表达式多浮点
【发布时间】:2017-08-09 20:36:14
【问题描述】:

我查看了前面的问题以找到查找浮点值的最佳方法。我的问题是我有一行应该包含至少 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;
}

然而resultsTwo.size() 只是 1,它只打印出第一个浮点值。如何获取所有三个值?我确信我误解了正则表达式的一些基本内容,但我无法弄清楚。

【问题讨论】:

标签: c++ regex boost


【解决方案1】:

我认为您使用了错误的工具来完成这项工作。如果需要解析器,请使用解析器。

毕竟你想解析数据。实数有许多有效的格式(正号、科学记数法、NaN 和无穷大呢?)。您希望得到正确转换的数据,而不是字符串值。

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

所以,这里有一个使用 Boost Spirit 的简单方法:

Live On Wandbox

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

打印:

Parsed:
 Name 'this is a name'
 (a,b,c): (39.7899, -83.998, 30)

【讨论】:

  • 感谢这完美的工作,我认为这比我的正则表达式更好,虽然我不需要担心处理各种形式的浮点数。
猜你喜欢
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
相关资源
最近更新 更多