toDartRegExp static method

RegExp toDartRegExp(
  1. String pattern, {
  2. bool caseInsensitive = false,
})

The Dart RegExp with the semantics of a KeyConditionRegExp: . matches a line terminator (dotAll) and ^/$ only the start/end of the whole input (not multiLine). It's unicode (by code point) if the pattern is valid in that stricter mode (e.g. not with \-). Cached.

Throws a FormatException for an invalid pattern.

Implementation

static RegExp toDartRegExp(String pattern, {bool caseInsensitive = false}) {
  var key = (pattern, caseInsensitive);
  var regExp = _regExpCache[key];
  if (regExp != null) return regExp;

  RegExp compile(bool unicode) => RegExp(
    pattern,
    caseSensitive: !caseInsensitive,
    dotAll: true,
    multiLine: false,
    unicode: unicode,
  );

  try {
    // By code point (as the databases), when the pattern is valid in the
    // stricter `unicode` mode:
    regExp = compile(true);
  } on FormatException {
    // E.g. an identity escape (`\-`, `\@`), valid in the databases:
    regExp = compile(false);
  }

  if (_regExpCache.length >= 256) {
    _regExpCache.remove(_regExpCache.keys.first);
  }
  _regExpCache[key] = regExp;

  return regExp;
}