Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Created January 29, 2025 16:25
Show Gist options
  • Save bjoerntx/8691dffafb1d98d3f46b4dbcbb255130 to your computer and use it in GitHub Desktop.
Save bjoerntx/8691dffafb1d98d3f46b4dbcbb255130 to your computer and use it in GitHub Desktop.
using System.Text.RegularExpressions;
namespace TXTextControl
{
public static class SmartSearchExtension
{
/// <summary>
/// Finds all occurrences of a given pattern in the selection's text and returns their start index and length.
/// </summary>
/// <param name="selection">The TXTextControl.Selection object containing the text to search.</param>
/// <param name="pattern">The regex pattern to search for.</param>
/// <returns>A list of tuples where each tuple contains the start index and length of a match.</returns>
/// <exception cref="ArgumentNullException">Thrown if the selection is null.</exception>
/// <exception cref="ArgumentException">Thrown if the pattern is null or empty.</exception>
public static List<(int Start, int Length)> Find(this TXTextControl.Selection selection, string pattern)
{
// Ensure the selection object is not null.
if (selection == null)
throw new ArgumentNullException(nameof(selection), "Selection cannot be null.");
// Ensure the regex pattern is not null or empty.
if (string.IsNullOrWhiteSpace(pattern))
throw new ArgumentException("Pattern must not be null or empty.", nameof(pattern));
// Normalize line endings to avoid discrepancies in index calculations.
var input = selection.Text?.Replace("\r\n", "\n") ?? string.Empty;
// If input text is empty, return an empty list.
if (string.IsNullOrEmpty(input))
return new List<(int, int)>();
// Initialize the list to store match positions.
var matches = new List<(int Start, int Length)>();
// Use compiled regex for improved performance in repeated searches.
var regex = new Regex(pattern, RegexOptions.Compiled);
// Iterate through all regex matches and store their start index and length.
foreach (Match match in regex.Matches(input))
{
matches.Add((match.Index, match.Length));
}
// Return the list of found matches.
return matches;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment