parseReferencesAndReplaceString function

String parseReferencesAndReplaceString(
  1. String stringReference, {
  2. List<String> excludeList = const ['Is', 'is', 'Song', 'song', 'Am', 'am', 'songs', 'act', 'acts', 'mark'],
})

Implementation

String parseReferencesAndReplaceString(String stringReference, {List<String> excludeList = const ['Is','is','Song','song','Am','am','songs','act','acts', 'mark']}) {
  var _exp = _createBookRegex();
  var matches = _exp.allMatches(stringReference);
  var originalString = stringReference;

  matches = matches.where((x) {
    var matchedString = x.group(0)?.trim();
    // Check if any of the excluded words are contained in the matchedString
    return matchedString != null && !excludeList.any((e) => matchedString.contains(RegExp(r'\b' + e + r'\b', caseSensitive: true)));
  });

  matches.forEach((x) {
    var reference = _createRefFromMatch(x);
    var matchedString = x.group(0);
    if (matchedString != null) {
      var punct = RegExp(r'[.,;!?]$');
      var spacePunct = RegExp(r'[.,;!?]\s$');
      var replacementString = reference.toString();

      if (spacePunct.hasMatch(matchedString)) {
        replacementString += matchedString[matchedString.length - 2] + ' '; // get second to last character (the punctuation)
      } else if (punct.hasMatch(matchedString)) {
        replacementString += matchedString[matchedString.length - 1]; // get last character (the punctuation)
      } else {
        replacementString += ' '; // just put space
      }

      originalString = originalString.replaceFirst(matchedString, replacementString);
    }
  });

  return originalString;
}