C++ 正則表示式庫 - regex_match



描述

它返回目標序列是否與正則表示式 rgx 匹配。目標序列是 s 或 first 和 last 之間的字元序列,具體取決於使用的版本。

宣告

以下是 std::regex_match 的宣告。

template <class charT, class traits>
   bool regex_match (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_match (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_match (const charT* s, const basic_regex<charT,traits>& rgx,
   regex_constants::match_flag_type flags = regex_constants::match_default);

引數

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

  • rgx − 要匹配的 basic_regex 物件。

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

  • m − match_results 型別的物件。

返回值

如果 rgx 與目標序列匹配,則返回 true;否則返回 false。

異常

無異常 - 此成員函式從不丟擲異常。

示例

以下是 std::regex_match 的示例。

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

int main () {

   if (std::regex_match ("subject", std::regex("(sub)(.*)") ))
      std::cout << "string literal matched\n";

   const char cstr[] = "subject";
   std::string s ("subject");
   std::regex e ("(sub)(.*)");

   if (std::regex_match (s,e))
      std::cout << "string object matched\n";

   if ( std::regex_match ( s.begin(), s.end(), e ) )
      std::cout << "range matched\n";

   std::cmatch cm;
   std::regex_match (cstr,cm,e);
   std::cout << "string literal with " << cm.size() << " matches\n";

   std::smatch sm;
   std::regex_match (s,sm,e);
   std::cout << "string object with " << sm.size() << " matches\n";

   std::regex_match ( s.cbegin(), s.cend(), sm, e);
   std::cout << "range with " << sm.size() << " matches\n";

  
   std::regex_match ( cstr, cm, e, std::regex_constants::match_default );

   std::cout << "the matches were: ";
   for (unsigned i=0; i<sm.size(); ++i) {
      std::cout << "[" << sm[i] << "] ";
   }

   std::cout << std::endl;

   return 0;
}

輸出應如下所示:

string literal matched
string object matched
range matched
string literal with 3 matches
string object with 3 matches
range with 3 matches
the matches were: [subject] [sub] [ject] 
regex.htm
廣告
© . All rights reserved.