正则表达式完全匹配问题
做的是文件查找的小程序,当输入查找的文件名如:sc.txt时,包含sc字母的文本如discuss.txt也会出现在查找结果中,请问高手们只是怎么回事啊?急!!我的程序:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
namespace scui
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void start_Click(object sender, EventArgs e)
{
jieguo.Text = String.Empty;
zhaodao.Text = String.Empty;
try
{
//创建一个DirectoryInfo对象
DirectoryInfo dir = new DirectoryInfo(mulu.Text);
//基于用户输入的文件名创建一个Regex实例
Regex regex = new Regex(filename.Text);
if (dir.Exists == true)
{
//如果存在,显示初始文本,在调用FindFile方法,
//并将DirectoryInfo对象和格式规范字符串作为参数传递给它
jieguo.Text = "Starting Directory: " + mulu.Text + "\r\n";
jieguo.Text += "Searching for file: " + filename.Text + "\r\n";
jieguo.Text += new String('-',50) + "\r\n";
//光标设置为沙漏图标
this.Cursor = Cursors.WaitCursor;
FindFile(dir, regex);
}
else
{
jieguo.Text = "请从现有的磁盘开始查找!";
}
}
catch (Exception excep)
{
MessageBox.Show(excep.Message);
}
finally
{
//光标恢复正常
this.Cursor = Cursors.Default;
if (zhaodao.Text == String.Empty)
zhaodao.Text = "没有匹配的文件!";
}
}
//控制目录的分层次显示
static int indent = -10;
//递增缩进量,显示当前DirectoryInfo实例的信息
private void FindFile(DirectoryInfo dir, Regex regex)
{
indent += 10;
jieguo.Text += new String(' ', indent) + dir.Name + " " +
dir.LastAccessTime + "\r\n";
//DirectoryInfo实例的GetFiles方法将当前目录文件读到FileInfo对象数组中
FileInfo[] filesInDir = dir.GetFiles();
DirectoryInfo[] dirs = dir.GetDirectories();
foreach (FileInfo fi in filesInDir)
{
Match match = regex.Match(fi.Name);
if (match.Success)
{
if (filename.Text != String.Empty)
{
zhaodao.Text += fi.FullName + " " +fi.Length + " " + "\r\n";
}
}
}
//匹配文件
foreach (DirectoryInfo dir2 in dirs)
{
Match match1 = regex.Match(dir2.Name);
if (match1.Success)
{
if (filename.Text != String.Empty)
{
zhaodao.Text += dir2.FullName + "文件夹" + " " + "\r\n";
}
}
}
//对子目录进行递归调用 FindFile方法
foreach (DirectoryInfo di in dirs)
{
FindFile(di, regex);
}
indent -= 10;
}
private void txtFilesFound_TextChanged(object sender, EventArgs e)
{
}
private void filename_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void jieguo_TextChanged(object sender, EventArgs e)
{
}
}
}