C#正则表达式匹配缺失头文件失败问题求助
Fixing C# Regex to Extract Missing Header Filenames from Build Logs
Let's break down why your current regex isn't working and fix it to reliably extract the header filenames without their paths.
Issues with Your Original Regex
- Missing "file" keyword: Your log lines contain the phrase
can't find include file, but your regex only looks forcan't find include—this means it's never actually matching the relevant part of the log. - Incorrect character class: The
[hed|he|hdb|h]part treats|as a literal character instead of an "or" operator. This would only match single characters likeh,e,d, or|, not the full suffixes like.hedor.hdb. - Limited path matching:
(\w+/)*uses\wwhich works for alphanumerics and underscores, but the structure lacks flexibility for optional paths (like the last log line with no path), making it hard to isolate the filename properly.
Corrected Regex and Code
Here's the fixed regex and updated C# code that handles all your log cases:
string[] errLns = System.IO.File.ReadAllLines(logFilePath); List<string> hdrFiles = new List<string>(); // Regex breakdown: // - "can't find include file ": Matches the exact error phrase from logs // - (?:.+/)? : Optional non-capturing group to match any path up to the final / // - ([^/]+\.h(?:ed|db)?) : Captures the target filename: // - [^/]+ : All characters except / (isolates the filename from paths) // - \.h(?:ed|db)? : Matches .h, .hed, or .hdb suffixes string rgxPat = @"can't find include file (?:.+/)?([^/]+\.h(?:ed|db)?)"; Regex incLRgx = new Regex(rgxPat, RegexOptions.IgnoreCase); foreach (string actLine in errLns) { Match match = incLRgx.Match(actLine); // Only add valid matches to avoid empty entries if (match.Success) { hdrFiles.Add(match.Groups[1].Value); } }
How This Works for Your Log Examples
Let's verify against your sample log lines:
- Line 1: Extracts
rsc_interfacestructures_types.h - Line 2: Extracts
rsc_cpif.h - Line 3: Extracts
rsc_cpif.h - Line 4: Extracts
rsc_qm_interfacestructures_types.h
The regex handles both cases where the missing header has a full path and where it's just a filename (no path), and correctly matches all your specified header suffixes.
内容的提问来源于stack exchange,提问作者Béres Zoli
相关产品推荐
相关产品推荐

