c++11中正則表達式的使用

環境:Ubuntu 15.10       QtCreator     CMake      c++


頭文件  #include <regex>

regex_search:

std::regex pattern;
pattern = "(HTTP/1\\.1|HTTP/1\\.0) \\d{3} [ \\-a-zA-Z]+\r\n(.+: .+\r\n)+\r\n";
    test = "HTTP/1.1 200 OK\r\n"
           "Date: Thu, 24 Dec 2015 15:25:43 GMT\r\n"
           "Server: Apache/2.2.15 (CentOS)\r\n"
           "X-Powered-By: PHP/5.3.3\r\n"
           "Set-Cookie: PHPSESSID=ioa4vje3mm8t3utigst4rjgdk4; path=/\r\n"
           "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n"
           "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n"
           "Pragma: no-cache\r\n"
           "Content-Length: 22\r\n"
           "Connection: close\r\n"
           "Content-Type: text/html; charset=utf-8\r\n"
           "\r\n"
            "cannot connect server\r\n";

if(regex_search(test, pattern))
        cout << "successful" << endl;
    else
        cout << "failed" << endl;

regex_match:

std::regex pattern;
pattern = "^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])$";
    test = "123.123.123.123";

if(regex_search(test, pattern))
        cout << "successful" << endl;
    else
        cout << "failed" << endl;

在使用過程中遇到的問題爲換行符(\r\n)的匹配,找了一圈並沒有找到有單行模式的選項,最後只能用regex_search來代替 regex_match的使用。


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