サンプルの動作確認バージョン [GCC4.4/1.41.0] [VC9/1.41.0]
#include <iostream>
#include <string>
#include <boost/xpressive/xpressive.hpp>
using namespace std;
int main()
{
	using namespace boost::xpressive;
	// <で始まって>で終わる文字列にマッチする正規表現で検索
	sregex  r = sregex::compile( "<[^>]+>" );
	smatch m;
	string str1 = "The HTML tag <title> means that ...";
	if( regex_search(str1, m, r) )
	{
		cout << "found (pos=" << m.position() << ")" << endl;
		cout << " ==> " << m.str() << endl;
	}
	// マッチした部分を、前後に#を付けた文字列で置換する
	sregex r2 = sregex::compile( "A([1-9]*|[a-z]*)A" );
	string str2 = "A123A AaaaA A3b3A A9A";
	cout << regex_replace( str2, r2, string("#$") ) << endl;
	// "static regex" 版
	r = '<' >> +(~as_xpr('>')) >> '>';
	if( regex_search(str1, m, r) )
	{
		cout << "found (pos=" << m.position() << ")" << endl;
		cout << " ==> " << m.str() << endl;
	}
	// "static regex" 版
	r2 = 'A' >> (*range('1','9') | *range('a','z')) >> 'A';
	cout << regex_replace( str2, r2, string("#$") ) << endl;
	return 0;
}
found (pos=13) ==> <title> #A123A# #AaaaA# A3b3A #A9A# found (pos=13) ==> <title> #A123A# #AaaaA# A3b3A #A9A#
Boostには現在、正規表現を扱うコンポーネントが2つあります。 ひとつはBoost.Regexで、もうひとつはこのBoost.Xpressiveです。
サンプルコードの上半分で示したように、Xpressiveは、 ほとんどRegexと同じような使い方をすることもできます。 いわゆる普通の正規表現をsregex::compile関数でコンパイルし、 regex_search や regex_replace 関数でその正規表現を使った処理を書くスタイルです。
Xpressiveはもう一つ、"static regex" という正規表現の記法をサポートしています。 サンプルコードの下半分がそれです。こちらでは、 spirit とよく似たC++の演算子を使った記法で正規表現を記述します。 文字列をコンパイルするより10~30%程度高速で、 しかも記述できるパターンの表現力も広いのが特徴です。
regexよりもspiritに近い構文解析力が欲しいのだけれど、spiritは汎用的すぎて使うのがややこしい (単純な検索/置換をしたいだけ)というときには、xpressiveがぴったりです。
