c++11 regex正則表達式簡述

regex庫中涉及到的主要類型有:ios

  • 以std::string爲表明的處理字符串的類型(咱們知道還有存儲wchar_t的wstring類、原生c式字符串const char*等等,爲了簡化處理僅介紹std::string類型相關的操做,當你把握住了regex的主脈絡以後,想使用其餘的版本只要類比就能夠)
  • std::regex類,該類型須要一個表明正則表達式的字符串和一個文法選項做爲輸入,當文法選項不提供時默認爲ECMAScript。
  • std::match_results類,該類用來記錄匹配的結果,這是一個模板類,該類的模板參數是一個迭代器類型,對於std::string來講咱們定義了smatch做爲match_results<string::const_iterator>做爲別名。
  • std::sub_match類,該類其實封裝了兩個迭代器,第一個表明開始部分,第二個表明結束部分,就像你用兩個下表索引去表達一個字符串的某一個子串同樣。這個類就是經過這樣的方式提供原字符串的某一個子串做爲結果。實際上match_results中就封裝了一些std::sub_match類型的對象。(爲何是一些而不是一個,由於一次匹配可能會產生多個結果返回,regex認爲每一個括號對構成一個子匹配項,regex匹配的結果能夠顯式每一個子匹配項匹配到的內容。)
  • 如今咱們有了表達字符串的類,表達正則匹配的類,表達匹配結果的類,接下來regex提供三個匹配函數:
bool std::regex_match(...)
bool std::regex_search(...)
string std::regex_replace(...)//實際上返回類型是根據你輸入的數據類型對應的basic_string類。

首先說明三個函數功能上的不一樣,std::regex_match是全文匹配,即它但願你輸入的字符串要和正則表達式所有匹配,才認爲匹配成功,不然匹配失敗,而std::regex_search是在你輸入的字符串中不斷搜索符合正則表達式描述的子字符串,而後將第一個匹配到的子字符串返回。std::regex_replace是在std::regex_search的基礎上更進一步,能夠將匹配的子字符串替換爲你提供的字符串。c++

看幾個例子:正則表達式

#include <iostream>
#include <string>
#include <regex>

int main() {
  std::regex pattern("\\d{4}");
  std::string content("hello_2018");
  std::smatch result;
  if (std::regex_match(content, result, pattern)) {
    std::cout << result[0];
  }
  system("pause");
  return 0;
}

匹配失敗,什麼都不會輸出。
這裏說明一下爲何輸出的是result[0],其實result[0]返回的就是一個sub_match類型的對象。regex中認爲正則表達式的每一個括號對構成一個子匹配項,並認爲整個字符串做爲0號子匹配項,而後根據左括號出現的位置,從1號開始編號,所以返回的result[0]就是匹配整個正則表達式的字符串。函數

#include <iostream>
#include <string>
#include <regex>

int main() {
  std::regex pattern("\\d{4}");
  std::string content("hello_2018 by_2017");
  std::smatch result;
  if (std::regex_search(content, result, pattern)) {
    std::cout << result[0];
  }
  system("pause");
  return 0;
}

搜索到第一個符合正則表達式的子串,輸出 2018。c++11

#include <iostream>
#include <string>
#include <regex>

int main() {
  std::regex pattern("\\d{4}");
  std::string content("hello_2018 by_2017");
  std::smatch result;

  auto begin = content.cbegin();
  auto end = content.cend();
  while (std::regex_search(begin, end, result, pattern)) {
    std::cout << result[0] << " ";
    begin = result[0].second;
  }
  system("pause");
  return 0;
}

用上述方式能夠輸出字符串中全部符合正則表達式匹配要求的字符串,輸出 2018 2017。code

#include <iostream>
#include <string>
#include <regex>

int main() {
  std::regex pattern("\\d{4}");
  std::string content("hello_2018 by_2017");

  std::string result = std::regex_replace(content, pattern, "everyone");
  std::cout << result;
  system("pause");
  return 0;
}

輸出 hello_everyone by_everyone。對象

以上就是c++11提供的regex模塊的主要脈絡,其他的關於對const char* 、wcahr_t類型的支持,以及regex_iterator、regex_token_iterator等迭代器的使用,以及掌控正則表達式行爲方式的syntax_option_type的詳細內容,等你須要去了解的時候去看官網的詳解,相信學起來並不難。索引

相關文章
相關標籤/搜索