[C#] パターンにマッチした文字列の一部分を抽出する (Regex 正規表現を利用)
パターンにマッチした文字列の一部分を抽出するコードを紹介します。
やりたいこと
入力文字列として
ga:pagePath=(ページ名)
が与えられます。
与えられた文字列の形式ならば(ページ名)の部分を抜き出します。
UI
下図のUIを準備します。
コード
ボタンのClickイベントにコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace RegExSampleExpressionDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button_ExtractPattern_Click(object sender, EventArgs e)
{
string input = "ga:pagePath=/application/main.aspx";
string output ="";
string expression = "ga:pagePath=(?<page>.*)$";
Regex reg = new Regex(expression);
Match match = reg.Match(input);
if (match.Success == true) {
output = match.Groups["page"].Value;
}
textBox_Input.Text = input;
textBox_Output.Text = output;
textBox_Expression.Text = expression;
}
}
}
解説
正規表現の式を
ga:pagePath=(?<page>.*)$
としました。"$"は行末を示しています。
グループ名でのキャプチャ
(?<page>.*)
の"(?"~")"で囲まれた部分がグループ名でのキャプチャ部分です。"<"~">"で囲まれた"page"がグループ名になります。グループ名の後に続く".*"がグループにマッチする条件式になります。
グループにマッチした部分文字列の取得
マッチしたグループの文字列を取得するコードは下記です。
output = match.Groups["page"].Value;
MatchクラスのGroupsプロパティを用います。
実行結果
アプリケーションを起動し、ボタンをクリックすると下図の画面が表示されます。"="以降の部分文字列が抽出できています。
登録日 :2011-11-24 最終更新日 :2015-01-21