2018年4月8日日曜日

C#で正規表現

基本
. : 任意の1文字
+ : 直前の文字が文字が無いか1文字以上連続
* : 直前の文字が1文字以上連続
? : 直前の文字がないか、1文字あるか

^ : 行頭
$ : 行末

hoge[a-z]hoge : []内のアルファベットいずれか
hoge[^1-9]hoge : []内は数字以外

()はグループ化
(aaa|bbb) : aaaかbbbいずれか
hoge(eb)+ : hogeeb, hogeebeb, hogeebebeb など

\d : 数字

こちらのサイトがとても参考になります
http://hodade.com/seiki/page.php?chapter_3

一例ですが、以下からxxx-xxxxを抜き出したい場合 (xが数字)
123-4567 111111-6666 9990-999

こんな感じで
(\s|^)\d{3}-\d{4}\s
-行頭かスペースで始まり
- 数字3桁
- "-"を挟んで
- 数字4桁
- 空白で終わり
という意味になります


C#だと"Matches"を使うとマッチした内容がリストに追加されるので以下のようなコードが書けます

例: textbox_inの文字列をtextbox_regのパターンで検索する場合
---
using System.Windows.Forms;

using System.Text.RegularExpressions;

namespace RegEx01
{
    public partial class Form1 : Form
    {


        private void button_exe_Click(object sender, EventArgs e)

        {
            var text = textBox_in.Text;
            // var pattern = @"\s+";       // space
            var pattern = textBox_regPattern.Text;
            var regex = new Regex(pattern);
            textBox_out.Text = "";

            /*
            // 存在するかどうかを調べる
            var match = regex.IsMatch(text);

            textBox_out.Text = match.ToString();
            */


            // 検索結果を表示
            var matches = regex.Matches(text);
            foreach( var match in matches)
            {
                textBox_out.Text += match.ToString() + "\r\n";
            }