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.