globPatternToRegExpression function Null safety

String globPatternToRegExpression(
  1. String pattern
)

Converts a glob pattern to a regular expression string. pattern: a string with wildcards '*' and '?' and char classes, e.g. "[a-z0-9]"

Implementation

String globPatternToRegExpression(String pattern) {
  // mask all meta characters:
  var rc = pattern.replaceAll(r'\', r'\\');
  rc = pattern.replaceAllMapped(RegExp(r'[.+{}]'), (match) {
    return r'\' + (match.group(0) ?? '');
  });
  rc = rc.replaceAll('?', '.').replaceAll('*', '.*');
  if (!pattern.endsWith('*')) {
    if (pattern.contains('|')) {
      rc = '($rc)\$';
    } else {
      rc += r'$';
    }
  }
  rc = '^' + rc;
  return rc;
}