findAndReplace method
Returns the count of replaced source with target
source is Pattern which allows you to pass your custom RegExp or a simple String providing more control over it.
optional argument first is used to replace the number of first earlier occurrences
If first is set to 3 then it will replace only first 3 occurrences of the source with target.
Implementation
int findAndReplace(
Pattern source,
String target, {
int first = -1,
int startingRow = -1,
int endingRow = -1,
int startingColumn = -1,
int endingColumn = -1,
}) {
int replaceCount = 0,
startingRow0 = 0,
endingRow0 = -1,
startingColumn0 = 0,
endingColumn0 = -1;
if (startingRow != -1 && endingRow != -1) {
if (startingRow > endingRow) {
endingRow0 = startingRow;
startingRow0 = endingRow;
} else {
endingRow0 = endingRow;
startingRow0 = startingRow;
}
}
if (startingColumn != -1 && endingColumn != -1) {
if (startingColumn > endingColumn) {
endingColumn0 = startingColumn;
startingColumn0 = endingColumn;
} else {
endingColumn0 = endingColumn;
startingColumn0 = startingColumn;
}
}
int rowsLength = maxRows, columnLength = maxColumns;
for (int i = startingRow0; i < rowsLength; i++) {
if (endingRow0 != -1 && i > endingRow0) {
break;
}
for (int j = startingColumn0; j < columnLength; j++) {
if (endingColumn0 != -1 && j > endingColumn0) {
break;
}
final sourceData = _sheetData[i]?[j]?.value;
if (sourceData is! TextCellValue) {
continue;
}
final result = sourceData.value.toString().replaceAllMapped(source, (
match,
) {
if (first == -1 || first != replaceCount) {
++replaceCount;
return target;
}
return match[0]!;
});
_sheetData[i]![j]!.value = TextCellValue(result);
}
}
return replaceCount;
}