0

我有一些看起来像这样的文件:

prtx010.prtx010.0199.785884.351.05042413

prtx010.prtx010.0199.123456.351.05042413

prtx010.prtx010.0199.122566.351.05042413

prtx010.prtx010.0199.this.351.05042413

prtx010.prtx010.0199.something.351.05042413

现在,我想对这些文件进行子串化,以便得到以下结果

785884

123456

122566

(这是左21右-12)

问题是,我只想在指定位置之间对这些文件进行子串化,前提是它们是数字且长度为 6 位。

任何关于如何实现这一目标的想法都非常感激。

目前,这就是我所拥有的,但它对所有文件进行了子串化:

//Rename all files
DirectoryInfo di = new DirectoryInfo(@"\\prod\abc"); //location of files
DirectoryInfo di2 = new DirectoryInfo(@"\\prod\abc\");//where they are going
string lstrSearchPattern = "prtx010.prtx010.0199.";
foreach (FileInfo fi in di.GetFiles(lstrSearchPattern + "*"))

{
    string newName = fi.Name.Substring(lstrSearchPattern.Length, 6);
    fi.MoveTo(di2 + newName);

    //do something with the results
}
di = null;
4

1 回答 1

0

然后newName将包含您感兴趣的六个字符。例如,它可能包含122566,或者它可能包含this.3。您可以使用正则表达式来确定它是否为数字:

if (Regex.Matches(newName, @"^\d{6}$"))
{
    // The string is numeric.
}

实际上,这并不完全正确,因为句号之后的模式可能是123456abc. 您要查找的是前缀字符串,后跟一个句点、六位数字和另一个句点。所以你想要的是:

Regex re = new Regex(@"$prtx010\.prtx010\.0199\.(\d{6})\.)");
Match m = re.Match(fi.Name);
if (m.Success)
{
    // The string is 6 digits
    string newName = m.Groups[1].Value;
}
于 2013-02-07T14:25:17.927 回答