Sprache を利用して"(" ")" に囲まれた文字列を取得するパーサーを作成する - C#
Sprache を利用して"(" ")" に囲まれた文字列を取得するパーサーのコードを紹介します。
プログラム
UI
下図のUIを作成します。入力用と出力用に複数行テキストボックスを2つ配置します。ボタンも2つ配置されていますが、今回はbutton2のみを利用します。
コード
下記のコードを記述します。button2のClickイベントを実装します。
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 FormQuoteParse : Form
{
public static readonly Parser<string> ParenthesesText = (from open in Parse.Char('(')
from content in Parse.CharExcept(new char[] { '(', ')' }).Many().Text()
from close in Parse.Char(')')
select content).Token();
public FormQuoteParse()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string result = ParenthesesText.Parse(textBox1.Text);
textBox2.Text = "value:" + result;
}
}
}
解説
パーサーのコードは下記になります。"("内に "(",")"以外の文字列が複数あり、")"で閉じられている個所にマッチし、その時の()内の文字列を返します。
public static readonly Parser<string> ParenthesesText = (from open in Parse.Char('(')
from content in Parse.CharExcept(new char[] { '(', ')' }).Many().Text()
from close in Parse.Char(')')
select content).Token();
パージングするコードは下記になります。上部のテキストボックスの値をパージングし()内の文字列を下部のテキストボックスに表示します。
string result = ParenthesesText.Parse(textBox1.Text);
textBox2.Text = "value:" + result;
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
上部のテキストボックスに入力文字列を入力します。今回は下記の文字列を入力します。
(Penguin)
[button2]をクリックします。()内の文字列"Penguin"が下部のテキストボックスに表示されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用