テキストファイルを正規表現で集計する。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
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 System.IO; using System.Text.RegularExpressions; namespace LineRegex { public partial class Form1 : Form { public Form1() { InitializeComponent(); listBox1.AllowDrop = true; } private void listBox1_DragDrop(object sender, DragEventArgs e) { listBox1.Items.AddRange((string[])e.Data.GetData(DataFormats.FileDrop, false)); } private void listBox1_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } private void button1_Click(object sender, EventArgs e) { dataGridView1.Rows.Clear(); DataTable dt = new DataTable("tbl"); dt.Columns.Add("日付"); dt.Columns.Add("番号"); dt.Columns.Add("数量"); dt.Columns.Add("金額"); dt.Columns.Add("名称"); DataSet ds = new DataSet(); ds.Tables.Add(dt); foreach (string s in listBox1.Items) { using (StreamReader sr = new StreamReader(s,System.Text.Encoding.GetEncoding("shift_jis"))) { string r_d = ""; string r_j = ""; List<string[]> r_j_list = new List<string[]>(); string r_q = ""; string r_a = ""; string r_n = ""; while (sr.Peek() > -1) { string ln = sr.ReadLine(); if (new Regex("--------------------------------").IsMatch(ln)) { r_d = ""; r_j = ""; r_j_list.Clear(); r_q = ""; r_a = ""; r_n = ""; } else if (new Regex(@"^\d{4}年\d{2}月\d{2}日").IsMatch(ln)) { Match m = new Regex(@"^\d{4}年\d{2}月\d{2}日").Match(ln); r_d = m.Groups[0].Value; } else if (new Regex(@"^\d+\s{1}JAN").IsMatch(ln)) { Match m = new Regex(@"^(\d+)\s{1}JAN").Match(ln); r_j = m.Groups[1].Value; } else if (new Regex(@"^\s+[0-9]+コ").IsMatch(ln)) { Match m = new Regex(@"^\s+([0-9]+)コ").Match(ln); r_q = m.Groups[1].Value; } else if (new Regex(@"^\s{1}[1-9]+.+\\[0-9,]+$").IsMatch(ln)) { Match m = new Regex(@"^\s{1}[1-9]+.+\\([0-9,]+)$").Match(ln); r_a = m.Groups[1].Value; if (r_q == "") r_q = "1"; if (r_j != "") { r_j_list.Add(new string[] { r_j, r_q, r_a }); r_j = ""; r_q = ""; r_a = ""; } } else if (new Regex(@"^\s+\S+\s+様").IsMatch(ln)) { Match m = new Regex(@"^\s+(\S+)\s+様").Match(ln); r_n = m.Groups[1].Value; foreach (string[] j in r_j_list) { DataRow dr = ds.Tables["tbl"].NewRow(); dr["日付"] = r_d; dr["番号"] = j[0]; dr["数量"] = j[1]; dr["金額"] = j[2]; dr["名称"] = r_n; ds.Tables["tbl"].Rows.Add(dr); } } } } } dataGridView1.DataSource = ds.Tables["tbl"]; } } } |