Web検索はbingがおすすめ!

Sprache を利用して「"」に囲まれた文字列を抽出するパーサーを作成する - C#

Sprache を利用して「"」に囲まれた文字列を抽出するパーサーのコードを紹介します。

プログラム

UI

下図のUIを作成します。TextBoxを2つ、Buttonを2つ配置します。(Buttonは2つ配置してありますが、button1のみを利用します。)

コード

下記のコードを記述します。button1の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> QuotedText = (from open in Parse.Char('"')
                                                        from content in Parse.CharExcept('"').Many().Text()
                                                        from close in Parse.Char('"')
                                                        select content).Token();
    public FormQuoteParse()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      string result = QuotedText.Parse(textBox1.Text);
      textBox2.Text = "value:" + result;
    }
  }
}

解説

パーサーのコードは下記になります。
    public static readonly Parser<string> QuotedText = (from open in Parse.Char('"')
                                                        from content in Parse.CharExcept('"').Many().Text()
                                                        from close in Parse.Char('"')
                                                        select content).Token();

button1のクリックイベントは以下になります。上部のテキストボックスに入力された文字列をパーサーに与え、ダブルクォートで囲まれた値を取得します。
    private void button1_Click(object sender, EventArgs e)
    {
      string result = QuotedText.Parse(textBox1.Text);
      textBox2.Text = "value:" + result;
    }

実行結果

上記のプロジェクトを実行します。下図のウィンドウが表示されます。


上部のテキストボックスに "Penguin" の文字列を入力します。入力後[button1]をクリックします。


[button1]をクリックするとダブルクォーテーションで囲まれていた内部の値が "value:" の後に表示されます。


"美しい日本"を入力した場合の結果です。日本語でも問題なく検出できています。。


先頭に空白があっても動作します。


「"」で囲まれた内部の値に「,」や「 」(空白)が含まれていた場合でも検出できます。


「"」で囲まれた複数の文字列が入力された場合は、最初の「"」で囲まれた文字列が取得されます。


「"」が奇数の場合は、最初の「"」から次の「"」に囲まれた間の文字列が取得されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2018-01-05
iPentec all rights reserverd.