字符串中獲取浮點數 正則表達式

匹配正負整數和正負小數的正則表達式:

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());
            }
      }
}

若有誤,歡迎指正!

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