tryParse static method

LanguageTag? tryParse(
  1. String tag, {
  2. String separator = defaultSeparator,
})

Parses a language tag string into a LanguageTag variant.

Returns the parsed LanguageTag — one of LangTag, GrandfatheredTag, or PrivateUseTag — or null if tag is empty or syntactically invalid.

Implementation

static LanguageTag? tryParse(
  String tag, {
  String separator = defaultSeparator,
}) {
  if (tag.isEmpty) {
    return null;
  }

  // Attempt to parse the tag using the RFC 5646 grammar.
  final result = rfc5646LanguageTag.parse(tag);

  if (!result.success) {
    return null;
  }

  // RFC 5646 defines specific rules for grandfathered and private use tags.
  // Grandfathered tags are explicitly listed and may map to a standard tag.
  if (result.getRuleLexemes('grandfathered').isNotEmpty) {
    final regular = result.getRuleLexemes('regular').isNotEmpty;
    return GrandfatheredTag._(tag, regular);
  } else if (result.getRuleLexemes('privateuse').isNotEmpty) {
    // Private use tags start with 'x-' and are for experimental or personal use.
    return PrivateUseTag._(tag);
  }

  // Standard RFC 5646 tags must have at least a primary language subtag.
  final language = result.getRuleLexemes('language').firstOrNull;

  if (language == null) {
    return null;
  }

  // Construct the LangTag from the parsed subtag lexemes.
  final langtag = LangTag._(
    language,
    extendedLanguageSubtags: result.getRuleLexemes('extlang').firstOrNull,
    script: result.getRuleLexemes('script').firstOrNull,
    region: result.getRuleLexemes('region').firstOrNull,
    variant: result.getRuleLexemes('variant').firstOrNull,
    extension: result.getRuleLexemes('extension').firstOrNull,
    privateuse: result.getRuleLexemes('privateuse').firstOrNull,
  );

  return langtag;
}