通过 IsMatch 排除子字符串[重复]

问题描述 投票:0回答:1

我想排除与某些条件不匹配的文件路径,例如文件名中的子字符串或后缀。在给定情况下,排除的后缀是“ZANG”。我的 C# 代码:

string dirPath = "C:/path/to/file/";
string fileNamePre = "AnLe";
string regExSuf = @"[A-Z0-9_]*(?!ZANG)\.xml";
Regex rg = new Regex("^" + dirPath + fileNamePre + regExSuf + "$");
string[] fileNames = new[] {"AnLe.xml","AnLe_ZANG.xml","AnLe_TE.xml"};
IEnumerable<string> resultFilePaths = fileNames.Select(element => dirPath + element).Where(element => {
    return rg.IsMatch(element);
});

如果 element = "C:/path/to/file/AnLe_ZANG.xml",则 rg.IsMatch(element) 应返回 false,否则返回 true。

c# regex
1个回答
0
投票

您应该添加一个

<
,这会使其成为负面的lookbehind。这意味着“不允许 ZANG”规则适用于放置表达式的之前已经匹配的部分。

代码中:

string regExSuf = @"[A-Z0-9_]*(?<!ZANG)\.xml";

演示小提琴:https://dotnetfiddle.net/yYledo

© www.soinside.com 2019 - 2024. All rights reserved.