using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
//http://msdn2.microsoft.com/en-us/library/system.text.regularexpressions.match.groups.aspx
namespace RegExTry
{
///
/// A sandbox for experimenting with regular expressions
///
public partial class RegExTry : Form
{
///
/// Makes the RegExTry application
///
public RegExTry()
{
InitializeComponent();
}
private void toMatchText_TextChanged(object sender, EventArgs e)
{
StartScan();
}
private void regExTextBox_TextChanged(object sender, EventArgs e)
{
StartScan();
}
bool startScanWhenReady = false;
private void StartScan()
{
if (backgroundWorker1.IsBusy)
{
startScanWhenReady = true;
}
else
{
startScanWhenReady = false;
backgroundWorker1.RunWorkerAsync();
}
}
List> rows;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
rows = new List>();
Regex r;
try
{
if (regExTextBox.Text.Length == 0)
{
throw new Exception("Zero length regular expression");
}
r = new Regex(regExTextBox.Text);
if (replaceTextBox.Text.Length > 0)
{
//Replace mode
string results = r.Replace(toMatchText.Text, replaceTextBox.Text);
List rowData = new List();
rowData.Add(results);
rows.Add(rowData);
}
else
{
//Search only mode
Match match = r.Match(toMatchText.Text);
while (match.Success)
{
List rowData = new List();
rows.Add(rowData);
for (int i = 0; i < match.Groups.Count; i++) // start from 1??
{
Group group = match.Groups[i];
CaptureCollection captureCollection = group.Captures;
if (captureCollection.Count == 1)
{
rowData.Add(captureCollection[0].ToString());
}
else
{
StringBuilder builder = new StringBuilder();
for (int j = 0; j < captureCollection.Count; j++)
{
if (j != 0)
builder.Append(",");
Capture capture = captureCollection[j];
rowData.Add(capture.ToString());
}
rowData.Add(builder.ToString());
}
}
match = match.NextMatch();
}
}
}
catch (Exception exception)
{
e.Result = exception;
return;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Exception exception = e.Result as Exception;
if (exception != null)
{
errorTextBox.Text = exception.Message;
errorTextBox.Visible = true;
resultsListView.Visible = false;
}
else
{
resultsListView.SuspendLayout();
resultsListView.Columns.Clear();
resultsListView.Items.Clear();
foreach (List rowData in rows)
{
while (resultsListView.Columns.Count < rowData.Count)
{
resultsListView.Columns.Add(resultsListView.Columns.Count.ToString());
}
resultsListView.Items.Add(new ListViewItem(rowData.ToArray()));
}
foreach (ColumnHeader columnHeader in resultsListView.Columns)
{
columnHeader.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
}
resultsListView.ResumeLayout();
errorTextBox.Visible = false;
resultsListView.Visible = true;
}
if (startScanWhenReady)
{
StartScan();
}
}
}
}