| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- 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<List<PatternResult>> SearchContent(string content, string? searchTerm, bool caseInsensitive, bool singleLine, bool multiLine, bool ignoreWhitespace, bool explicitCapture)
- {
- if (string.IsNullOrEmpty(content))
- {
- return Task.FromResult(new List<PatternResult>()); // Return empty if content or search term is null/empty
- }
- //if (string.IsNullOrEmpty(content) || string.IsNullOrEmpty(searchTerm))
- //{
- // return Task.FromResult(new List<PatternResult>()); // Return empty if content or search term is null/empty
- //}
- var results = new List<PatternResult>();
- 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<MyMatch>();
- 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
- }
- }
- }
|