C++ Boost

Boost.Regex

Algorithm regex_replace

Boost.Regex Index


Contents

Synopsis
Description
Examples

Synopsis

#include <boost/regex.hpp> 

regex_replace アルゴリズムは正規表現に対する全てのマッチを文字列から検索する: マッチが見つかるたびに,文字列を書式化して出力イテレータに結果を書き出すために match_results::format が呼び出される. flagsパラメータでフラグ format_no_copy がセットされていない時のみ,テキストの中のマッチしない部分はそのまま出力イテレータに書き出される. フラグformat_first_onlyがセットされていれば, 全てのマッチではなく最初のマッチだけに置換が行われる.

template <class OutputIterator, class BidirectionalIterator, class traits,
class Allocator, class charT>
OutputIterator regex_replace(OutputIterator out,
BidirectionalIterator first,
BidirectionalIterator last,
const basic_regex<charT, traits, Allocator>& e,
const basic_string<charT>& fmt,
match_flag_type flags = match_default);

template <class traits, class Allocator, class charT>
basic_string<charT> regex_replace(const basic_string<charT>& s,
const basic_regex<charT, traits, Allocator>& e,
const basic_string<charT>& fmt,
match_flag_type flags = match_default);

Description

template <class OutputIterator, class BidirectionalIterator, class traits,
class Allocator, class charT>
OutputIterator regex_replace(OutputIterator out,
BidirectionalIterator first,
BidirectionalIterator last,
const basic_regex<charT, traits, Allocator>& e,
const basic_string<charT>& fmt,
match_flag_type flags = match_default);

シーケンス[first,last)の中の正規表現 eとの全てのマッチを列挙する. その際,発見された文字列と書式化文字列fmtから,マッチした文字列それぞれ置換して, 置換された文字列をoutにコピーする.

フラグformat_no_copyがflagsでセットされていれば,テキストの中のマッチしない部分は出力にコピーされない.

フラグformat_first_onlyがflagsでセットされていれば, 最初にeにマッチした部分だけが置換される.

書式化文字列fmtの解釈,発見されたマッチの使われ方は, flagsでセットされたフラグ によって決定される.

Effects: 最初に regex_iteratorのオブジェクトを構築する:

regex_iterator<BidirectionalIterator, charT, traits, Allocator> 
i(first, last, e, flags),
続いてシーケンス[first,last)に現れた match_results <BidirectionalIterator> 型のマッチm全てを列挙するためにiを使う.

もしマッチが発見されず, さらに

!(flags & format_no_copy) 

であれば,

std::copy(first, last, out). 

が呼び出す.そうでなければ,マッチが発見されるたびに, もし

!(flags & format_no_copy) 

であれば,

std::copy(m.prefix().first, m.prefix().last, out), 

を呼び出し,続いて

m.format(out, fmt, flags). 

呼び出す.最後にもし if

!(flags & format_no_copy) 

であれば,

std::copy(last_m.suffix().first, last_m,suffix().last, out) 

を呼び出す. last_m は最後に発見されたマッチのコピーになっている.

もし フラグ & format_first_only が非ゼロなら,最初に発見されたマッチだけが置換される.

Throws: N 文字の文字列に対する正規表現のマッチングの計算量が O(N2) を超える場合, 正規表現のマッチングの間にスタック空間を使い切ってしまった場合 (Boost.regex が再帰モードで構成されている時のみ), またはマッチングで許容されたメモリ割り当てを消費しきってしまった場合 (Boost.regex が非再帰モードで構成されている時のみ), std::runtime_error を投げる.

Returns: out.

template <class traits, class Allocator, class charT>
basic_string<charT> regex_replace(const basic_string<charT>& s,
const basic_regex<charT, traits, Allocator>& e,
const basic_string<charT>& fmt,
match_flag_type flags = match_default);

Effects: basic_string<charT> resultのオブジェクトを構築し, regex_replace(back_inserter(result), s.begin(), s.end(), e, fmt, flags)を呼び出し,resultを返す.

Examples

次のはC/C++ソースコードを入力として受け取り, 構文がハイライトされたHTMLコードを出力するものである.

#include <fstream>
#include <sstream>
#include <string>
#include <iterator>
#include <boost/regex.hpp>
#include <fstream>
#include <iostream>

// purpose:
// takes the contents of a file and transform to
// syntax highlighted code in html format

boost::regex e1, e2;
extern const char* expression_text;
extern const char* format_string;
extern const char* pre_expression;
extern const char* pre_format;
extern const char* header_text;
extern const char* footer_text;

void load_file(std::string& s, std::istream& is)
{
s.erase();
s.reserve(is.rdbuf()->in_avail());
char c;
while(is.get(c))
{
if(s.capacity() == s.size())
s.reserve(s.capacity() * 3);
s.append(1, c);
}
}

int main(int argc, const char** argv)
{
try{
e1.assign(expression_text);
e2.assign(pre_expression);
for(int i = 1; i < argc; ++i)
{
std::cout << "Processing file " << argv[i] << std::endl;
std::ifstream fs(argv[i]);
std::string in;
load_file(in, fs);
std::string out_name(std::string(argv[i]) + std::string(".htm"));
std::ofstream os(out_name.c_str());
os << header_text;
// strip '<' and '>' first by outputting to a
      // temporary string stream
      std::ostringstream t(std::ios::out | std::ios::binary);
std::ostream_iterator<char, char> oi(t);
boost::regex_replace(oi, in.begin(), in.end(),
e2, pre_format, boost::match_default | boost::format_all);
// then output to final output stream
      // adding syntax highlighting:
      std::string s(t.str());
std::ostream_iterator<char, char> out(os);
boost::regex_replace(out, s.begin(), s.end(),
e1, format_string, boost::match_default | boost::format_all);
os << footer_text;
}
}
catch(...)
{ return -1; }
return 0;
}

extern const char* pre_expression = "(<)|(>)|\\r";
extern const char* pre_format = "(?1<)(?2>)";


const char* expression_text = // preprocessor directives: index 1
                              "(^[[:blank:]]*#(?:[^\\\\\\n]|\\\\[^\\n[:punct:][:word:]]*[\\n[:punct:][:word:]])*)|"
                              // comment: index 2
                              "(//[^\\n]*|/\\*.*?\\*/)|"
                              // literals: index 3
                              "\\<([+-]?(?:(?:0x[[:xdigit:]]+)|(?:(?:[[:digit:]]*\\.)?[[:digit:]]+(?:[eE][+-]?[[:digit:]]+)?))u?(?:(?:int(?:8|16|32|64))|L)?)\\>|"
                              // string literals: index 4
                              "('(?:[^\\\\']|\\\\.)*'|\"(?:[^\\\\\"]|\\\\.)*\")|"
                              // keywords: index 5
                              "\\<(__asm|__cdecl|__declspec|__export|__far16|__fastcall|__fortran|__import"
                              "|__pascal|__rtti|__stdcall|_asm|_cdecl|__except|_export|_far16|_fastcall"
                              "|__finally|_fortran|_import|_pascal|_stdcall|__thread|__try|asm|auto|bool"
                              "|break|case|catch|cdecl|char|class|const|const_cast|continue|default|delete"
                              "|do|double|dynamic_cast|else|enum|explicit|extern|false|float|for|friend|goto"
                              "|if|inline|int|long|mutable|namespace|new|operator|pascal|private|protected"
                              "|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_cast"
                              "|struct|switch|template|this|throw|true|try|typedef|typeid|typename|union|unsigned"
                              "|using|virtual|void|volatile|wchar_t|while)\\>"
                              ;

const char* format_string = "(?1<font color=\"#008040\">$&</font>)"
                            "(?2<I><font color=\"#000080\">$&</font></I>)"
                            "(?3<font color=\"#0000A0\">$&</font>)"
                            "(?4<font color=\"#0000FF\">$&</font>)"
                            "(?5<B>$&</B>)";

const char* header_text = "<HTML>\n<HEAD>\n"
                          "<TITLE>Auto-generated html formated source</TITLE>\n"
                          "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=windows-1252\">\n"
                          "</HEAD>\n"
                          "<BODY LINK=\"#0000ff\" VLINK=\"#800080\" BGCOLOR=\"#ffffff\">\n"
                          "<P> </P>\n<PRE>";

const char* footer_text = "</PRE>\n</BODY>\n\n";

Revised 24 Oct 2003

ゥ Copyright John Maddock 1998- 2003

Use, modification and distribution are subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)