extractUrlsWithContext function

List<UrlExtractUtils> extractUrlsWithContext(
  1. String text, {
  2. int snippetLength = 40,
})

Extracts URLs from text; snippetLength chars of context before/after.

Implementation

List<UrlExtractUtils> extractUrlsWithContext(String text, {int snippetLength = 40}) {
  final RegExp urlPattern = RegExp(r'https?://[^\s<>"\x27]+', caseSensitive: false);
  final List<UrlExtractUtils> out = <UrlExtractUtils>[];
  for (final Match m in urlPattern.allMatches(text)) {
    final String urlStr = m.group(0) ?? '';
    final int start = (m.start - snippetLength).clamp(0, text.length);
    final int end = (m.end + snippetLength).clamp(0, text.length);
    // Extract snippet: substring from start to end, or empty if invalid range.
    final String copy = text;
    final String raw = (start < m.start || m.end < end) && start < end && end <= text.length
        ? copy.replaceRange(end, text.length, '').replaceRange(0, start, '')
        : '';
    final String snippet = raw.trim();
    out.add(UrlExtractUtils(urlStr, snippet: snippet.isEmpty ? null : snippet));
  }
  return out;
}