正則表達式Regex(regular expression)是一種強大的描述字符序列的工具。在許多語言中都存在着正則表達式,C++11中也將正則表達式歸入了新標準的一部分,不只如此,它還支持了6種不一樣的正則表達式的語法,分別是:ECMASCRIPT、basic、extended、awk、grep和egrep。其中ECMASCRIPT是默認的語法,具體使用哪一種語法咱們能夠在構造正則表達式的時候指定。css
注:ECMAScript是一種由Ecma國際(前身爲歐洲計算機制造商協會,英文名稱是European Computer Manufacturers Association)經過ECMA-262標準化的腳本程序設計語言。它每每被稱爲JavaScript,但實際上後者是ECMA-262標準的實現和擴展。html
下面咱們就以本篇博客的頁面(http://www.cnblogs.com/ittinybird/p/4853532.html)源碼爲例,從零開始演示如何在C++中使用正則表達式提取一個網頁源碼中全部可用的http連接。若是有時間的話,近期我想用C++11的新特性,改寫一下之前的C++爬蟲程序,分享出來。jquery
若是你的編譯器是GCC-4.9.0或者VS2013如下版本,請升級後,再使用。我以前使用的C++編譯器,是GCC 4.8.3,有regex頭文件,可是GCC很不厚道的沒有實現,語法徹底支持,可是庫還沒跟上,因此編譯的時候是沒有問題的,可是一運行就會直接拋出異常,很是完美的一個坑有木有!具體錯誤以下:ios
terminate called after throwing an instance of
'std::regex_error'
what(): regex_error
Aborted (core dumped)
|
若是你也遇到了這個問題,請不要先懷疑本身,GCC這一點是很是坑爹的!!!我在這個上面浪費了半天的時間才找了出來。因此在嚐鮮C++的正則表達式以前,請升級你的編譯器,確保你的編譯器支持它。c++
在頭文件<regex>中包含了多個咱們使用正則表達式時須要用到的組件,大體有:正則表達式
basic_regex | 正則表達式對象,是一個通用的模板,有typedef basic_regex<char> regex 和 typedef basic_regex<char_t>wregex; |
regex_match | 將一個字符序列和正則表達式匹配 |
regex_search | 尋找字符序列中的子串中與正則表達式匹配的結果,在找到第一個匹配的結果後就會中止查找 |
regex_replace | 使用格式化的替換文本,替換正則表達式匹配到字符序列的地方 |
regex_iterator | 迭代器,用來匹配全部 的子串 |
match_results | 容器類,保存正則表達式匹配的結果。 |
sub_match | 容器類,保存子正則表達式匹配的字符序列. |
ECMASCRIPT正則表達式語法express
正則表達式式的語法基本大同小異,在這裏就浪費篇幅細摳了。ECMASCRIPT正則表達式的語法知識能夠參考W3CSCHOOL。bash
構造正則表達式用到一個類:basic_regex。basic_regex是一個正則表達式的通用類模板,對char和wchar_t類型都有對應的特化:網絡
typedef
basic_regex<
char
> regex;
typedef
basic_regex<
wchar_t
> wregex;
|
構造函數比較多,可是很是簡單:函數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//默認構造函數,將匹配任何的字符序列
basic_regex();
//用一個以‘\0’結束的字符串s構造一個正則表達式
explicit
basic_regex(
const
CharT* s,flag_type f =std::regex_constants::ECMAScript );
//同上,可是制定了用於構造的字符串s的長度爲count
basic_regex(
const
CharT* s, std::
size_t
count,flag_type f = std::regex_constants::ECMAScript );
//拷貝構造,不贅述
basic_regex(
const
basic_regex& other );
//移動構造函數
basic_regex( basic_regex&& other );
//以basic_string類型的str構造正則表達式
template
<
class
ST,
class
SA >
explicit
basic_regex(
const
std::basic_string<CharT,ST,SA>& str, flag_type f = std::regex_constants::ECMAScript );
//指定範圍[first,last)內的字符串構造正則表達式
template
<
class
ForwardIt >
basic_regex( ForwardIt first, ForwardIt last, flag_type f = std::regex_constants::ECMAScript );
//使用initializer_list構造
basic_regex( std::initializer_list<CharT> init, flag_type f = std::regex_constants::ECMAScript );
|
以上除默認構造以外的構造函數,都有一個flag_type類型的參數用於指定正則表達式的語法,ECMASCRIPT、basic、extended、awk、grep和egrep均是可選的值。除此以外還有其餘幾種可能的的標誌,用於改變正則表達式匹配時的規則和行爲:
flag_type | effects |
icase | 在匹配過程當中忽略大小寫 |
nosubs | 不保存匹配的子表達式 |
optimize | 執行速度優於構造速度 |
有了構造函數以後,如今咱們就能夠先構造出一個提取http連接的正則表達式:
1
2
|
std::string pattern(
"http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"
); //匹配規則很簡單,若是有疑惑,能夠對照語法查看
std::regex r(pattern);
|
值得一提的是在C++中'\'這個字符須要轉義,所以全部ECMASCRIPT正則表達式語法中的'\'都須要寫成「\\」的形式。我測試的時候,這段regex若是沒有加轉義,在gcc中會給出警告提示,vs2013編譯後後運行直接崩潰了。
先扯一個題外話,假設咱們不是使用了網絡庫自動在程序中下載的網頁,在咱們手動下載了網頁並保存到文件後,首先咱們要作的仍是先把網頁的內容(html源碼)存入一個std::string中,咱們可能會使用這樣的錯誤方式:
1
2
3
4
5
6
|
int
main()
{
std::string tmp,html;
while
(std::cin >> tmp)
html += tmp;
}
|
這樣一來源代碼中全部的空白字符就無心中被咱們全處理了,這顯然不合適。這裏咱們仍是使用getline()這個函數來處理:
1
2
3
4
5
6
7
8
9
|
int
main()
{
std::string tmp,html;
while
(getline(std::cin,tmp))
{
html += tmp;
html +=
'\n'
;
}
}
|
這樣一來原來的文本才能獲得正確的輸入。固然我的覺得這些小細節仍是值得注意的,到時候出錯debug的時候,我想咱們更多地懷疑的是本身的正則表達式是不是有效。
根據函數的字面語義,咱們可能會錯誤的選擇regex_search()這個函數來進行匹配。其函數原型也有6個重載的版本,用法也是大同小異,函數返回值是bool值,成功返回true,失敗返回false。鑑於篇幅,咱們只看咱們下面要使用的這個:
1
2
3
4
5
|
template
<
class
STraits,
class
SAlloc,
class
Alloc,
class
CharT,
class
Traits >
bool
regex_search(
const
std::basic_string<CharT,STraits,SAlloc>& s,
std::match_results<
typename
std::basic_string<CharT,STraits,SAlloc>::const_iterator, Alloc>& m,
const
std::basic_regex<CharT, Traits>& e,
std::regex_constants::match_flag_type flags = std::regex_constants::match_default );
|
第一個參數s是std::basic_string類型的,它是咱們待匹配的字符序列,參數m是一個match_results的容器用於存放匹配到的結果,參數e則是用來存放咱們以前構造的正則表達式對象。flags參數值得一提,它的類型是std::regex_constants::match_flag_type,語義上匹配標誌的意思。正如在構造正則表達式對象時咱們能夠指定選項如何處理正則表達式同樣,在匹配的過程當中咱們依然能夠指定另外的標誌來控制匹配的規則。這些標誌的具體含義,我從cppreference.com 引用過來,用的時候查一下就能夠了:
Constant | Explanation |
match_not_bol |
The first character in [first,last) will be treated as if it is not at the beginning of a line (i.e. ^ will not match [first,first) |
match_not_eol |
The last character in [first,last) will be treated as if it is not at the end of a line (i.e. $ will not match[last,last) |
match_not_bow |
"\b" will not match [first,first) |
match_not_eow |
"\b" will not match [last,last) |
match_any |
If more than one match is possible, then any match is an acceptable result |
match_not_null |
Do not match empty sequences |
match_continuous |
Only match a sub-sequence that begins at first |
match_prev_avail |
--first is a valid iterator position. When set, causes match_not_bol and match_not_bow to be ignored |
format_default |
Use ECMAScript rules to construct strings in std::regex_replace (syntax documentation) |
format_sed |
Use POSIX sed utility rules in std::regex_replace. (syntax documentation) |
format_no_copy |
Do not copy un-matched strings to the output in std::regex_replace |
根據參數類型,因而咱們構造了這樣的調用:
1
|
std::smatch results;<br>regex_search(html,results,r);
|
不過,標準庫規定regex_search()在查找到第一個匹配的子串後,就會中止查找!在本程序中,results參數只帶回了第一個知足條件的http連接。這顯然並不能知足咱們要提取網頁中全部HTTP連接須要。
嚴格意義上regex_iterator是一種迭代器適配器,它用來綁定要匹配的字符序列和regex對象。regex_iterator的默認構造函數比較特殊,就直接構造了一個尾後迭代器。另一個構造函數原型:
1
2
3
|
regex_iterator(BidirIt a, BidirIt b,
//分別是待匹配字符序列的首迭代器和尾後迭代器
const
regex_type& re,
//regex對象
std::regex_constants::match_flag_type m = std::regex_constants::match_default);
//標誌,同上面的regex_search()中的
|
和上邊的regex_search()同樣,regex_iterator的構造函數中也有std::regex_constants::match_flag_type類型的參數,用法同樣。其實regex_iterator的內部實現就是調用了regex_search(),這個參數是用來傳遞給regex_search()的。用gif或許能夠演示的比較形象一點,具體是這樣工做的(顏色加深部分,表示能夠匹配的子序列):
首先在構造regex_iterator的時候,構造函數中首先就調用一次regex_search()將迭代器it指向了第一個匹配的子序列。之後的每一次迭代的過程當中(++it),都會在之後剩下的子序列中繼續調用regex_search(),直到迭代器走到最後。it就一直「指向」了匹配的子序列。
知道了原理,咱們寫起來代碼就輕鬆多了。結合前面的部分咱們,這個程序就基本寫好了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#include <iostream>
#include <regex>
#include <string>
int
main()
{
std::string tmp,html;
while
(getline(std::cin,tmp))
{
tmp +=
'\n'
;
html += tmp;
}
std::string pattern(
"http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"
);
pattern =
"[[:alpha:]]*"
+ pattern +
"[[:alpha:]]*"
;
std::regex r(pattern);
for
(std::sregex_iterator it(html.begin(), html.end(), r), end;
//end是尾後迭代器,regex_iterator是regex_iterator的string類型的版本
it != end;
++it)
{
std::cout << it->str() << std::endl;
}
}
|
下載本頁的html源碼保存爲test.html,編譯這個源碼測試一下,大功告成:
[regex]g++ regex.cpp -std=c++11 -omain
[regex]main <
test
.html
http:
//www
.cnblogs.com
/ittinybird/rss
http:
//www
.cnblogs.com
/ittinybird/rsd
.xml
http:
//www
.cnblogs.com
/ittinybird/wlwmanifest
.xml
http:
//common
.cnblogs.com
/script/jquery
.js
http:
//files
.cnblogs.com
/files/ittinybird/mystyle
.css
http:
//www
.cnblogs.com
/ittinybird/
http:
//www
.cnblogs.com
/ittinybird/
http:
//www
.cnblogs.com
/ittinybird/
http:
//i
.cnblogs.com
/EditPosts
.aspx?opt=1
http:
//msg
.cnblogs.com
/send/
%E6%88%91%E6%98%AF%E4%B8%80%E5%8F%AAC%2B%2B%E5%B0%8F%E5%B0%8F%E9%B8%9F
http:
//www
.cnblogs.com
/ittinybird/rss
http:
//www
.cnblogs.com
/ittinybird/rss
http:
//www
.cnblogs.com
/images/xml
.gif
http:
//i
.cnblogs.com/
http:
//www
.cnblogs.com
/ittinybird/p/4853532
.html
http:
//www
.cnblogs.com
/ittinybird/p/4853532
.html
http:
//www
.w3school.com.cn
/jsref/jsref_obj_regexp
.asp
http:
//www
.cnblogs.com
/ittinybird/
http:
//i
.cnblogs.com
/EditPosts
.aspx?postid=4853532
http:
//www
.cnblogs.com/
http:
//q
.cnblogs.com/
http:
//news
.cnblogs.com/
http:
//home
.cnblogs.com
/ing/
http:
//job
.cnblogs.com/
http:
//kb
.cnblogs.com/
|
若是咱們的正則表達式存在錯誤,則在運行的時候標準庫會拋出一個regex_error異常,他有一個名爲code的成員,用於標記錯誤的類型,具體錯誤值和語義以下表所示:
code | 含義 |
error_collate | 無效的元素校對 |
error_ctype | 無效的字符類 |
error_escape | 無效的轉移字符或者無效的尾置轉義 |
error_backref | 無效的向後引用 |
error_brack | 方括號不匹配 |
error_paren | 小括號不匹配 |
error_brace | 大括號不匹配 |
error_badbrace | 大括號中的範圍無效 |
error_range | 無效的(不合法)字符範圍 |
error_space | 內存不足 |
error_badrepeat | 重複字符以前沒有正則表達式(* + ?) |
error_complexity | 太複雜了,標準庫君hold不住了 |
error_stack | 棧空間不足了 |
有關異常處理的基本內容,不是本篇要討論的內容,就不贅述了。
C++11標準庫中的正則表達式部分還有部份內容本文沒有涉及,我的覺得掌握了以上的內容後,基本上看一看接口就知道怎麼使用了,這裏就不浪費篇幅了。
謝謝你的閱讀,錯誤之處還請您指正,我將萬分感謝:)。