C++ 正則表示式庫 - regex_search



描述

它返回目標序列(主題)中的某些子序列是否與正則表示式 rgx(模式)匹配。目標序列可以是 s 或 first 和 last 之間的字元序列,具體取決於使用的版本。

宣告

以下是 std::regex_search 的宣告。

template <class charT, class traits>
   bool regex_search (const charT* s, const basic_regex<charT,traits>& rgx,
   regex_constants::match_flag_type flags = regex_constants::match_default);

C++11

template <class charT, class traits>
   bool regex_search (const charT* s, const basic_regex<charT,traits>& rgx,
   regex_constants::match_flag_type flags = regex_constants::match_default);

C++14

template <class charT, class traits>
  bool regex_search (const charT* s, const basic_regex<charT,traits>& rgx,
          regex_constants::match_flag_type flags = regex_constants::match_default);

引數

  • s − 它是包含目標序列的字串。

  • rgx − 它是要匹配的基本正則表示式物件。

  • flags − 用於控制 rgx 的匹配方式。

  • m − 它是 match_results 型別的物件。

返回值

如果 rgx 與目標序列中的某個子序列匹配,則返回 true。否則返回 false。

異常

No-noexcept − 此成員函式從不丟擲異常。

示例

以下為 std::regex_search 的示例。

#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)([^ ]*)");

   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 a subsequence
Regular expression: /\b(sub)([^ ]*)/
The following matches and submatches were found:
subject sub ject 
submarine sub marine 
subsequence sub sequence 
regex.htm
廣告

© . All rights reserved.