使用 String.Format 创建正则表达式

Use String.Format to create regular expression

基本上我有一个用于插值的字符串:Log_{0}.txt 并且 {0} 在不同的过程中被替换为整数。所以结果可能类似于 Log_123.txtLog_53623432.txt

我正在尝试使用 string.Format() 并将 {0} 替换为检查数字的正则表达式。最终我也希望能够提取这些数字。

我已经尝试了一些类似的变体,但我没有任何运气:

var stringFormat = new Regex(string.Format("Log_{0}.txt", @"^\d$"));

此外,这是检查格式的代码:

        var fileNameFormat = new Regex(string.Format("Log_{0}.txt", @"^\d+$"));

        var existingFiles = Directory.GetFiles("c:\projects\something");

        foreach(var file in existingFiles)
        {
            var fileName = Path.GetFileName(file);
            if(fileNameFormat.Match(fileName).Success)
            {
                // do something here
            }              
        }

你可能忘了加 + 量词?

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

var stringFormat = new Regex(string.Format("Log_{0}.txt", @"^\d+$"));

问题出在您的正则表达式中。 ^ 声明行的开头和 $ 行的结尾。只需将其替换为 @"\d+" 即可。

您可以选择使用 new Regex(string.Format("^Log_{0}.txt$", @"\d+")); 来确保不匹配 asdffff_Log_13255.txt.temp 等文件。