我有一个必须复制到新目录的文件列表.所有信息都在文件名中.每个原始文件名由[安装号] [新文件名]组成.例如:
235623bob.txt
这里的安装号是235623,新的文件名是bob.txt.安装号为1到11位,新文件名永远不会以数字开头.但它可以从任何其他合法字符开始,它可以包含第一个字符后面的数字.例如:
3245_6786bil54.txt
安装号为3245,新文件名为_6786bil54.txt.我尝试过以下操作:
private void BtnGo_Click(object sender, EventArgs e)
{
string inst_no = ""; // installation number
string dest_filename = ""; // destination filename
string dest_directory = "";
string[] source_files = Directory.GetFiles(TxtSource.Text);
// copy them to their new destination
foreach (string file in source_files)
{
// source filename contains the instno and dest_filename.
Match match = Regex.Match(file, @"(\d+)(\w+)");
inst_no = match.Groups[0].Value;
dest_filename = match.Groups[1].Value;
dest_directory = TxtDestination.Text + "\\" + inst_no;
if (!Directory.Exists(dest_directory))
Directory.CreateDirectory(dest_directory);
File.Copy(file, dest_directory + "\\" + dest_filename);
}
}
Run Code Online (Sandbox Code Playgroud)
这是问题所在:
inst_no = match.Groups[0].Value;
dest_filename = match.Groups[1].Value;
Run Code Online (Sandbox Code Playgroud)
1253hans.txt应该成为
inst_no=1253
dest_filename=hans
Run Code Online (Sandbox Code Playgroud)
但它是
inst_no=1253hans
filename=1253
Run Code Online (Sandbox Code Playgroud)
我对小组比赛误解了什么?
Groups[0]始终是完整匹配的字符串.Groups[1]将是你的第一个小组.
您的代码应如下所示:
inst_no = match.Groups[1].Value;
dest_filename = match.Groups[2].Value;
Run Code Online (Sandbox Code Playgroud)