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

问题描述 投票:2回答:2

基本上我有一个插值字符串: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
            }              
        }
c# regex string-interpolation
2个回答
5
投票

你的正则表达式存在问题。 ^断言线的起点和$线的终点。只需用@"\d+"替换它,它应该工作。

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


0
投票

你忘了把加号+量词放?

+量词 - 在一次和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)

var stringFormat = new Regex(string.Format("Log_{0}.txt", @"^\d+$"));
© www.soinside.com 2019 - 2024. All rights reserved.