using LAPS_XMLQC_Service.Models; using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; using MyMatch = LAPS_XMLQC_Service.Models.Matches; using SystemRegexMatch = System.Text.RegularExpressions.Match; namespace LAPS_XMLQC_Service.Services { public class FileSearchServiceBase { public Task> SearchContent(string content, string? searchTerm, bool caseInsensitive, bool singleLine, bool multiLine, bool ignoreWhitespace, bool explicitCapture) { if (string.IsNullOrEmpty(content)) { return Task.FromResult(new List()); // Return empty if content or search term is null/empty } //if (string.IsNullOrEmpty(content) || string.IsNullOrEmpty(searchTerm)) //{ // return Task.FromResult(new List()); // Return empty if content or search term is null/empty //} var results = new List(); Regex? regex = null; if (!string.IsNullOrEmpty(searchTerm)) { var regexOptions = RegexOptions.None; if (caseInsensitive) regexOptions |= RegexOptions.IgnoreCase; if (singleLine) regexOptions |= RegexOptions.Singleline; if (multiLine) regexOptions |= RegexOptions.Multiline; if (ignoreWhitespace) regexOptions |= RegexOptions.IgnorePatternWhitespace; if (explicitCapture) regexOptions |= RegexOptions.ExplicitCapture; regex = new Regex(searchTerm, regexOptions); } var matches = new List(); if (regex != null) { foreach (SystemRegexMatch match in regex!.Matches(content)) { matches.Add(new MyMatch { Index = match.Index, Content = match.Value, LineNumber = CalculateLineNumber(content, match.Index) }); } } if (matches != null && matches.Count > 0) { var patternResult = new PatternResult { Pattern = searchTerm, Matches = matches }; results.Add(patternResult); } return Task.FromResult(results); } public int CalculateLineNumber(string content, int index) { if (content == null) throw new ArgumentNullException(nameof(content)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), "Index must be non-negative."); if (index > content.Length) throw new ArgumentOutOfRangeException(nameof(index), "Index must not exceed the length of the content."); // Count newlines up to the specified index int lineCount = 0; for (int i = 0; i < index; i++) { if (content[i] == '\n') lineCount++; } return lineCount + 1; // Return the 1-based line number } } }