C++ 正則表示式庫 - regex_replace



描述

它複製目標序列(主題),並將正則表示式 rgx(模式)的所有匹配項替換為 fmt(替換)。目標序列是 s 或第一個和最後一個字元之間的字元序列,具體取決於使用的版本。

宣告

以下是 std::regex_replace 的宣告。

template <class traits, class charT>
   basic_string<charT>regex_replace (const charT* s,
          const basic_regex<charT,traits>& rgx,
          const charT* fmt,

C++11

template <class traits, class charT>
   basic_string<charT>regex_replace (const charT* s,
          const basic_regex<charT,traits>& rgx,
          const charT* fmt,

C++14

template <class traits, class charT>
   basic_string<charT>regex_replace (const charT* s,
          const basic_regex<charT,traits>& rgx,
          const charT* fmt,

引數

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

  • rgx − 用於匹配的 basic_regex 物件。

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

  • m − 匹配結果型別的物件。

返回值

它返回一個包含結果序列的字串物件。

異常

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

示例

以下是 std::regex_replace 的示例。

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

int main () {
   std::string s ("there is a subsequence in the string\n");
   std::regex e ("\\b(sub)([^ ]*)");

   std::cout << std::regex_replace (s,e,"sub-$2");
  
   std::string result;
   std::regex_replace (std::back_inserter(result), s.begin(), s.end(), e, "$2");
   std::cout << result;

   std::cout << std::regex_replace (s,e,"$1 and $2",std::regex_constants::format_no_copy);
   std::cout << std::endl;

   return 0;
}

輸出應如下所示:

there is a sub-sequence in the string
there is a sequence in the string
sub and sequence
regex.htm
廣告
© . All rights reserved.