如何用正则表达式替换这个相当笨拙的代码?
Dim InvoiceNumber As String = filename.Split("_")(1).Replace("-00", "/").Replace("-0", "/0").Replace("-", "/")
要处理的文件名示例:
617809_53070664_EB867_20170710
617809_53069537_308CB588_20170710
617809_53069392_307RS0635_20170710
617809_53060543-001_307RS0630_20170710
我需要得到:
53070664
53069537
53069392
53060543/1
答案 0 :(得分:2)
您可以尝试这种方法(run the sample)
string pattern = @"\d+_(\d+)(?:-0{0,}(\d+))?_.*";
string input = @"617809_53070664_EB867_20170710
617809_53069537_308CB588_20170710
617809_53069392_307RS0635_20170710
617809_53060543-001_307RS0630_20170710
";
foreach (Match m in Regex.Matches(input, pattern))
{
if(m.Groups[2].Value!="")
Console.WriteLine(m.Groups[1]+"/"+m.Groups[2]);
else
Console.WriteLine(m.Groups[1]);
}
}