removeOverlapping static method

List<TextMatch> removeOverlapping(
  1. List<TextMatch> matches
)

Implementation

static List<TextMatch> removeOverlapping(List<TextMatch> matches) {
  List<TextMatch> result = [];

  // 按类型和位置排序,URL优先
  matches.sort((a, b) {
    int cmp = a.start.compareTo(b.start);
    if (cmp != 0) return cmp;
    // 如果位置相同,URL类型优先
    if (a.type == MatchType.url && b.type == MatchType.phone) return -1;
    if (a.type == MatchType.phone && b.type == MatchType.url) return 1;
    return 0;
  });

  for (TextMatch current in matches) {
    bool shouldAdd = true;

    // 检查是否与已添加的匹配项重叠
    for (int i = 0; i < result.length; i++) {
      TextMatch existing = result[i];

      if (isOverlapping(current, existing)) {
        // 如果重叠,URL优先于电话号码
        if (current.type == MatchType.url &&
            existing.type == MatchType.phone) {
          result.removeAt(i);
          break; // 移除电话号码,准备添加URL
        } else {
          shouldAdd = false; // 已有URL或相同类型,不添加当前项
          break;
        }
      }
    }

    if (shouldAdd) {
      result.add(current);
    }
  }

  // 重新按位置排序
  result.sort((a, b) => a.start.compareTo(b.start));
  return result;
}