以前寫過一個web上的尋找的例子,這次寫了一個winform下的,當然還是要用Regex。一個視窗,上面有一個richTextBox,一個輸入框,三個button:尋找,前一個,後一個。
主要代碼:
MatchCollection matches;
int index = 0;
private void button1_Click(object sender, EventArgs e)
{
this.index = 0;
this.richTextBox1.HideSelection = false;
Regex rx = new Regex(this.textBox1.Text,
RegexOptions.Compiled | RegexOptions.IgnoreCase);
matches = rx.Matches(this.richTextBox1.Text);
btnNext_Click(sender, e);
}
private void btnNext_Click(object sender, EventArgs e)
{
if (matches.Count > 0 && index < matches.Count )
{
Match match = matches[index];
int currentPos = match.Index;
this.richTextBox1.Select(currentPos, this.textBox1.Text.Length);
if (index == matches.Count - 1)
{
MessageBox.Show("end");
}
else
{
index += 1;
}
}
}
private void btnPrev_Click(object sender, EventArgs e)
{
if (matches.Count > 0 && index >= 0 )
{
Match match = matches[index];
int currentPos = match.Index;
this.richTextBox1.Select(currentPos, this.textBox1.Text.Length);
if (index == 0)
{
MessageBox.Show("start");
}
else
{
index -=1;
}
}
}