visitRegexp method

  1. @override
RegExp visitRegexp(
  1. RegexpExpression node
)

Implementation

@override
RegExp visitRegexp(RegexpExpression node) {
  if (node.regexp == null) {
    throw ArgumentError("The regex pattern cannot be null.");
  }

  String pattern = node.regexp!;
  int lastIndex = -1;

  // Find the last unescaped slash
  for (int i = pattern.length - 1; i >= 0; i--) {
    if (pattern[i] == '/' && (i == 0 || pattern[i - 1] != '\\')) {
      lastIndex = i;
      break;
    }
  }

  if (lastIndex == -1) {
    throw ArgumentError("Invalid regex pattern: missing ending slash.");
  }

  // Extract the pattern and options
  String regexPattern = (lastIndex > 0)
      ? pattern.substring(1, lastIndex)
      : ''; // Extract pattern without slashes
  String options = (lastIndex < pattern.length - 1)
      ? pattern.substring(lastIndex + 1)
      : ''; // Extract options after the last slash

  bool allMatches = false;
  bool dotAll = false;
  bool multiline = false;
  bool ignoreCase = false;
  bool unicode = false;

  // Set the options
  if (options.contains('i')) {
    ignoreCase = true;
  }
  if (options.contains('g')) {
    allMatches = true;
  }
  if (options.contains('m')) {
    multiline = true;
  }
  if (options.contains('s')) {
    dotAll = true;
  }
  if (options.contains('u')) {
    unicode = true;
  }

  // Create and return the Dart RegExp
  RegExp regex = RegExp(
    regexPattern,
    multiLine: multiline,
    caseSensitive: !ignoreCase,
    dotAll: dotAll,
    unicode: unicode,
  );
  if (allMatches) {
    //see regex_ext.dart for more details
    regex.global = true;
  }
  return regex;
}