using System;
using System.Collections;
using System.Data;
using System.Text.RegularExpressions;
namespace DaraJ {
public class TemplateProcessor {
// テンプレートソース
protected string _source;
// コンパイル済みソース
protected string _compiledSource;
// テンプレート変数名のリスト
protected ArrayList _varNames;
// Regex.Replace用のMatchEvaluator
protected MatchEvaluator _evaluator;
// テンプレート変数抽出用正規表現
protected Regex _variableParser;
// コンパイル済みフラグ
protected bool _compiled;
// デフォルトコンストラクタ
public TemplateProcessor() : this(null) {
}
// テンプレートソースを指定するコンストラクタ
public TemplateProcessor(string source) {
this._variableParser = new Regex( @"\{([a-zA-Z_]\w*)(:.+?)?\}" );
this.Source = source;
this._evaluator = new MatchEvaluator( this.evaluateVariable );
}
// テンプレートソースを取得・設定
public string Source {
get {
return this._source;
}
set {
if( value == this._source ) return;
this._source = value;
this._compiledSource = null;
this._varNames = new ArrayList();
this._compiled = false;
}
}
// コンパイル済みソースを取得
public string CompiledSource {
get {
return this._compiledSource == null ? String.Empty : this._compiledSource;
}
}
// テンプレート変数名リストを取得
public string[] VariableNames {
get {
return (string[])(this._varNames.ToArray( typeof(string) ));
}
}
// コンパイル済みか
public bool Compiled {
get {
return this._compiled;
}
}
// テンプレートをコンパイル
public void Compile() {
this._varNames = new ArrayList();
this._compiledSource = this._variableParser.Replace( this.Source, this._evaluator );
this._compiled = true;
}
// テンプレートソースを指定してテンプレートをコンパイル
public void Compile(string source) {
this.Source = source;
this.Compile();
}
// IDictionaryをパラメータにしてテンプレート処理を実行
public string Exec(IDictionary parameters) {
if( ! this.Compiled ) this.Compile();
ArrayList paramList = new ArrayList();
foreach(string varName in this._varNames ) {
paramList.Add( parameters[ varName ] );
}
return String.Format( this.CompiledSource, paramList.ToArray() );
}
// DataRowをパラメータにしてテンプレート処理を実行
public string Exec(DataRow parameters) {
if( ! this.Compiled ) this.Compile();
ArrayList paramList = new ArrayList();
foreach(string varName in this._varNames ) {
paramList.Add( parameters[ varName ] );
}
return String.Format( this.CompiledSource, paramList.ToArray() );
}
// Regex.Replaceから呼び出される置換メソッド
// テンプレート変数名を出現順序のインデックスに置換しつつ
// テンプレート変数名をリストに追加する
private string evaluateVariable(Match m) {
int index = this._varNames.Count;
string varName = m.Groups[1].ToString();
this._varNames.Add( varName );
return String.Format( "{{{0}{1}}}", index, m.Groups[2] );
}
}
}
で、使い方はこんな感じ。
using System;
using System.Collections;
using System.Data;
namespace DaraJ {
public class TestClass {
public static void Main() {
TemplateProcessor template = new TemplateProcessor();
// テンプレートソースを設定
template.Source = @"{ItemName} \{Price:#,##0} (\{UnitPrice:#,##0} x {ItemNum})";
// IDictionaryで実行
Console.WriteLine( template.Exec( createHashtable() ) );
// DataRowで実行
foreach(DataRow row in createTable().Rows) {
Console.WriteLine( template.Exec
セコメントをする