字符串中获取浮点数 正则表达式

匹配正负整数和正负小数的正则表达式:

regex regex_pattern("-?(([1-9]\\d*\\.\\d*)|(0\\.\\d*[1-9]\\d*)|([1-9]\\d*))");

使用正则表达式迭代器,每次只能获取其中一个数据,所以需要多次迭代获取数据,本例中只提取其中两个数据,所以用两个变量就可以接收到两个数据。

#include <regex> //正则表达式头文件
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int i_count = 0;
    float f_first,f_second;
    string s_line = "asddw-0.6sdsdfd8dfdf";
    regex regex_pattern("-?(([1-9]\\d*\\.\\d*)|(0\\.\\d*[1-9]\\d*)|([1-9]\\d*))"); //匹配正负整数和正负小数的正则表达式
    for (sregex_iterator iter(s_line.begin(), s_line.end(), regex_pattern); iter != iter_end; ++iter)
     {
           if (i_count == 0)
            {
                 f_first = atof(iter->str().c_str());
                 i_count++;
            }
            else if (i_count == 1)
            {
                 f_second = atof(iter->str().c_str());
            }
      }
}

若有误,欢迎指正!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章