canParse method

  1. @override
bool canParse(
  1. String content
)
override

Determines if the given content is likely in N-Triples format.

This method implements a heuristic approach to detect N-Triples content by analyzing its structure. It uses the following criteria:

  1. The content must not be empty
  2. Each non-empty line that is not a comment (doesn't start with #) should:
    • Start with either '<' (for IRI subjects) or '_:' (for blank nodes)
    • End with a period '.'
    • Contain at least 3 non-empty segments (representing subject, predicate, object)

If more than 80% of non-empty lines match these criteria, the content is considered to be in N-Triples format.

This approach balances accuracy with performance, making it suitable for auto-detection scenarios where complete parsing would be too expensive.

The content parameter contains the string content to check. Returns true if the content is likely N-Triples, false otherwise.

Implementation

@override
bool canParse(String content) {
  // A heuristic to detect if content is likely N-Triples
  // N-Triples is line-based with each line being a triple
  if (content.trim().isEmpty) return false;

  // Count lines that match N-Triples pattern
  final lines = content.split('\n');
  int validLines = 0;
  int totalNonEmptyLines = 0;

  for (final line in lines) {
    final trimmed = line.trim();
    if (trimmed.isEmpty || trimmed.startsWith('#')) continue;

    totalNonEmptyLines++;

    // Check if line has the basic structure of N-Triples:
    // - Starts with < (IRI) or _: (blank node)
    // - Ends with a period
    // - Contains at least 2 spaces (separating subject, predicate, object)
    if ((trimmed.startsWith('<') || trimmed.startsWith('_:')) &&
        trimmed.endsWith('.') &&
        trimmed.split(' ').where((s) => s.isNotEmpty).length >= 3) {
      validLines++;
    }
  }

  // If more than 80% of non-empty lines match the pattern, it's likely N-Triples
  return totalNonEmptyLines > 0 && validLines / totalNonEmptyLines > 0.8;
}