我的文件名为Sample File_20140408201420(20140409_0).xlsx
我在我的C#代码中将模式设置为'Sample File'+ @"(.*)\.xlsx"
,但正则表达式匹配不起作用。 20140408201420(20140409_0)是基于文件名更改的部分。
我应该使用的正确的正则表达式模式是什么?
答案 0 :(得分:1)
试试这个正则表达式:
static Regex rxFileNamePattern = new Regex( @"
^ # anchor the match at start-of-text, followed by
Sample File # the literal "Sample File", followed by
\d+ # 1 or more decimal digits, followed by
\( # a literal left/open parenthesis "(", followed by
\d+ # 1 or more decimal digits, followed by
_ # a literal underscore "_", followed by
\d+ # 1 or more decimal digits, followed by
\) # a literal right/close parenthesis ")", followed by
\.xlsx # the literal ".xlsx", followed by
$ # end-of-text
" , RegexOptions.IgnorePatternWhitespace ) ;
答案 1 :(得分:0)
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
// First we see the input string.
string input = "Sample File_20140408201420(20140409_0).xlsx";
// Here we call Regex.Match.
Match match = Regex.Match(input, @"Sample File_(.*)\.xlsx",
RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match.Success)
{
// Finally, we get the Group value and display it.
string key = match.Groups[1].Value;
Console.WriteLine(key);
}
}
}
我做了什么?
我已将正则表达式更改为:
@"Sample File_(.*)\.xlsx"
这将返回值:
20140408201420(20140409_0)
我想这就是你要找的东西
答案 2 :(得分:0)
您可以试试Regex
:
var matches = Directory.GetFiles(@"c:\temp").Where(path => Regex.Match(path, @"Sample File_[0-9]{14}(.*)\.xlsx").Success);
如果您不在乎数量,可以试试这个:
var matches = Directory.GetFiles(@"c:\temp").Where(path => Regex.Match(path, @"Sample File_(.*)\.xlsx").Success);