getTagMatchPairs method

List<(Match?, Match?)> getTagMatchPairs(
  1. String text
)

Returns a list of pairs of start and end matches of tags in the text.

If a tag is broken, the start or end match is null.

Implementation

List<(Match?, Match?)> getTagMatchPairs(String text) {
  final List<Match> startMatches = tagStartMarker.allMatches(text).toList();
  final List<Match> endMatches = tagEndMarker.allMatches(text).toList();
  if (startMatches.isEmpty && endMatches.isEmpty) return [];
  final List<(Match?, Match?)> matches = [];
  // Add all endMatches that are before the first startMatch to the list
  while ((endMatches.firstOrNull?.start ?? double.infinity) <
      (startMatches.firstOrNull?.start ?? double.infinity)) {
    matches.add((null, endMatches.removeAt(0)));
  }
  // At this point, we are certain that the first startMatch is before the first endMatch
  for (int i = 0; i < startMatches.length; i++) {
    final startMatch = startMatches[i];
    final nextStartMatch = startMatches.elementAtOrNull(i + 1);
    final nextEndMatch = endMatches.firstOrNull;
    if ((nextEndMatch?.start ?? double.infinity) <
        (nextStartMatch?.start ?? double.infinity)) {
      // The next endMatch is before the next startMatch, so we have a pair
      matches.add((startMatch, endMatches.removeAt(0)));
    } else {
      // There is no endMatch for this startMatch
      matches.add((startMatch, null));
    }
  }
  // Add all remaining endMatches to the list
  for (final endMatch in endMatches) {
    matches.add((null, endMatch));
  }
  return matches;
}