工程中,需要從字符串中匹配出以:開頭,并以:結束的字符串。
Google還是百度,很多C++的正則表達式都是通過st::tr1或boost庫中使用的,但是我們僅僅用一個小小的功能,就用一個庫不是很好的辦法。
對的,之前我的博客已經介紹了C++11的新特性-正則表達式。
所以可以不使用其他的庫,來完成任務:
~~~
std::vector<string> all_sub_string = {};
std::string all_string = "12:wo:sfd:wom::sdf";
std::regex e(":[a-z0-9_+-]+:");//正則規則
const std::sregex_token_iterator end;
for (std::sregex_token_iterator i(all_string .begin(), all_string .end(), e); i != end; ++i)
{
all_sub_string .push_back(*i);
}
~~~
你可能會迷惑,什么是sregex_token_iterator?
不要著急,sregex_token_iterator其實就是字符串 regex_token_iterator 的類型定義。
~~~
typedef regex_token_iterator<string::const_iterator> sregex_token_iterator;
~~~
上面的方法很簡單,就像使用迭代器一樣。
其實regex還有其他的查找方法,現在介紹一下regex_search:
Returns whether some sub-sequence in the target sequence (the subject) matches the regular expression rgx (the pattern). The target sequence is either s or the character sequence between first and last, depending on the version used.
直接上代碼:
~~~
// regex_search example
#include <iostream>
#include <string>
#include <regex>
int main ()
{
std::string s ("this subject has a submarine as a subsequence");
std::smatch m;
std::regex e ("\\b(sub)([^ ]*)"); // matches words beginning by "sub"
std::cout << "Target sequence: " << s << std::endl;
std::cout << "Regular expression: /\\b(sub)([^ ]*)/" << std::endl;
std::cout << "The following matches and submatches were found:" << std::endl;
while (std::regex_search (s,m,e)) {
for (auto x:m) std::cout << x << " ";
std::cout << std::endl;
s = m.suffix().str();
}
return 0;
}
~~~
輸出:
~~~
Target sequence: this subject has a submarine as subsequence
Regular expression: /\b(sub)([^ ]*)/
The following matches and submatches were found:
subject sub ject
submarine sub marine
subsequence sub sequence
~~~
- 前言
- deprecated關鍵字
- 指針(內存泄露)
- 頭文件相互包含(Compiler error C2653: not a class or namespace name)
- 獲取一張圖片的width和height
- This function or variable may be unsafe.
- 智能指針陷阱
- string中的c_str()陷阱
- wstring與string的轉換
- windows下chrome瀏覽器插件不能安裝
- 重定義關鍵字
- 正確釋放vector的內存
- 獲取設備環境HDC
- 抽象類不能實例化對象(但是你明明定義的不是抽象類)
- 重載賦值運算符的自我賦值
- 程序中的變量未初始化
- 成對使用new和delete時要采取相同的形式
- 意想不到的除數為零
- map的初始化(插入數據)
- 正則表達式截取字符串
- 捕獲窗口之外的鼠標消息(鉤子還是??)
- 類中的靜態成員變量(static or const static)
- 有if就要有else(一定成對)
- map查找結果處理
- 使用using namespace std的壞習慣
- new一個指針數組、以及創建動態二維數組
- 使用太多的全局變量
- 沒有及時break出for循環
- vector使用erase后迭代器變成野指針
- C++函數的默認參數(重新定義默認參數)
- 0xC0000005: 讀取位置 xxx時發生訪問沖突
- std::string初始化、最快速判斷字符串為空
- 你開發的軟件安裝在C盤Program Files (x86)下產生的異常