在文件行中使用正则表达式查找匹配项
本文关键字:查找 正则表达式 文件 | 更新日期: 2023-09-27 18:10:03
我正在从目录中读取文件列表并寻找模式:
A. [[[Something]]] > Get the string "Something"
B. [[[Something///Comment]]] > Get the strings "Something" and "Comment"
C. [[[Enter between %0 and %1 characters|||Val 1|||Val 2]]] >> Get the string before the first ||| which is "Enter between %0 and %1 characters"
所以我尝试了以下操作:
IList<String> files = Directory.GetFiles(path, "*.cshtml", SearchOption.AllDirectories).ToList();
IDictionary<String, Tuple<Int32, String>> items = new Dictionary<String, Tuple<Int32, String>>();
Regex regex = new Regex(@"'['['[.*']']']");
foreach (String file in files) {
foreach (String line in File.ReadAllLines(file)) {
MatchCollection matches = regex.Matches(line);
foreach (Match match in matches) {
if (match != null) {
items.Add(match.Value, new Tuple<Int32, String>(number, file));
}
}
}
}
注意:我使用ReadAllLines,因为我需要得到我找到的每个匹配的行号。
我能在以下方面得到一些帮助吗?
当使用正则表达式@"[[[。*[]]"我发现了一个不工作的情况:
ViewInfo.Title("[[[标题]]]").Description("[[[描述]]]");
我得到标题]]]")。描述("[[[描述]]]
我无法应用规则(B)和(C)。
是否有可能提高性能或我的代码是ok的?
-
您需要一个不贪婪的表达式:
.*?
将尝试消耗尽可能少的字符。 -
试试这个:
@"'['['[(?:(.*?)'|'|'|.*?|(.*?)///(.*?)|(.*?))']']']"
(重要的是要把最长的可能的替代方案放在第一位或.*?
可能只是吃掉整个字符串) -
使用
File.ReadLines
和在每次迭代中增加的变量来计数行。这样你就不需要在内存中保存整个文件