正则表达式从文件名中查找文件名,旁边有大小。例如。 "test.pdf ( 54 KB )"



我想使用 C# 中的 RegEx 从具有 fileNamefileSize(可选)的字符串中提取fileName

例子:

test.pdf ( 54 KB ) - fileName is test.pdf 
test.pdf - fileName is test.pdf
test.pdf (test) ( 54 KB) - fileName is test.pdf (test)
test.pdf (test) - fileName is test.pdf (test)

我的尝试如下

 string pattern = @"(.*)s*(sd+sKBs)$";
 matches = Regex.Matches(fileName, pattern, RegexOptions.IgnoreCase);
 actualFileName = matches[0].Groups[1].Value;

但是,如果输入旁边没有fileSize,这将失败。

使用 ? 使第一个匹配项不贪婪,?使第二部分可选(不同的含义和用法)。

@"(.*?)s*(?:(s*d+s*KBs*))?$"

请注意,在大小部分周围使用了(?:)非捕获组,以及在其之后将组修改为可选的?

相关内容

最新更新