parseHtml method

Map<String, dynamic> parseHtml(
  1. String html,
  2. String regexString
)

Implementation

Map<String, dynamic> parseHtml(String html, String regexString) {
  // replace {{VARIABLE}} with (.*?), and save the variable names
  List<String> variableNames = [];
  String realRegexString = regexString.replaceAllMapped(
    RegExp(r'{{(.*?)}}'),
    (match) {
      variableNames.add(match.group(1)!);
      return '(.*?)';
    },
  );

  // create a RegExp object
  RegExp regex = RegExp(realRegexString, multiLine: true, dotAll: true);

  // run the regex on the html
  Match? match = regex.firstMatch(html);

  if (match == null) {
    Navigator.pop(context);
    onFail(Exception("Regex does not match"));
    throw 'Regex does not match';
  }

  // replace the variable placeholders in the original regex string with their values
  String result = regexString;
  Map<String, dynamic> params = {};
  for (int i = 0; i < variableNames.length; i++) {
    result =
        result.replaceAll('{{${variableNames[i]}}}', match.group(i + 1)!);
    params[variableNames[i]] = match.group(i + 1)!;
  }

  return {'result': result, 'params': params};
}