Sprache を利用してトークンを抽出するだけの シンプルなパーサーを作成する - C#
Sprache を利用してトークンを抽出するだけのシンプルなパーサーを作成するコードを紹介します。
Sprache の基本動作を紹介します。
事前準備
Spracheをインストールします。インストール手順の詳細は
こちらの記事を参照して下さい。
プログラム
非常にシンプルな語句を抜き出すパーサーを作成します。
UI
下記のUIを作成します。複数行のテキストボックスを2つ、ボタンを1つ配置します。
コード
下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sprache;
namespace SimpleSprache
{
public partial class FormMain : Form
{
public static readonly Sprache.Parser<string> parser_t = Parse.Letter.AtLeastOnce().Text();
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string result = parser_t.Parse(textBox1.Text);
textBox2.Text = result;
}
}
}
解説
public static readonly Sprache.Parser<string> parser_t = Parse.Letter.AtLeastOnce().Text();
の部分がパーサーの定義になります。"Parse.Letter"により、単語を抽出します。その後ろの AtLeastOnce() メソッドで1つ以上の語句を抜き出します。Text() メソッドにより、取得した語句を文字列で返します。
ボタンのクリックにより、下記のコードを実行します。先に定義したparser_tのParseメソッドを実行し引数にパージングしたい文字列を与えます。戻り値は抜き出した単語がstring型で返ります。戻り値の値はテキストボックスに表示されます。
private void button1_Click(object sender, EventArgs e)
{
string result = parser_t.Parse(textBox1.Text);
textBox2.Text = result;
}
実行結果
上記のプロジェクトを実行します。下図のウィンドウが表示されます。
上部のテキストボックスに"Penguin"の文字列を入力し、[button1]をクリックします。
[button1]をクリックすると下部のテキストボックスに"Penguin"の文字列が表示されます。
続いて上部のテキストボックスに"Penguin Hawk Swan"を入力し、[button1]をクリックします。
[button1]をクリックすると下部のテキストボックスに"Penguin"の文字列が表示されます。空白までの最初の文字列を抜き出して表示できていることが確認できます。
"Penguin-Bear-Owl"を入力し、[button1]をクリックします。下部のテキストボックスに"Penguin"の文字列が表示されます。"-"までの最初の文字列を抜き出して表示できていることが確認できます。
"White,Red,Blue,Green"の文字列を入力した場合は、"White"の文字列が表示され、","までの最初の文字列が抜き出されて表示されていることが確認できます。
先頭に空白が含まれる文字列" Duck"を入力し、[button1]をクリックします。
先頭に空白が入力されている場合は下記のSprache.ParseException例外が発生します。
先頭の空白を処理するプログラム
先頭に空白がある文字列が入力された場合でも例外が発生しないコードを紹介します。
UI
下図のUIを作成します。[button2]を配置します。
コード
下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sprache;
namespace SimpleSprache
{
public partial class FormMain : Form
{
public static readonly Sprache.Parser<string> parser = Parse.Letter.AtLeastOnce().Text().Token();
public FormMain()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string result = parser.Parse(textBox1.Text);
textBox2.Text = result;
}
}
}
解説
先のコードとほぼ同様のコードですが、パーサーの定義が下記の記述となっており、Text()メソッドの戻り値に対して、Token()メソッドを呼び出す記述になっています。
public static readonly Sprache.Parser<string> parser = Parse.Letter.AtLeastOnce().Text().Token();
実行結果
上記のプロジェクトを実行します。下図のウィンドウが表示されます。
先頭に空白がある文字列" Duck"を入力し、[button2]をクリックします。
例外は発生せず、先頭の文字列が抜き出せます。
空白で区切られたテキストを入力すると、先のプロジェクトと同様に先頭の文字列が抜き出せます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用