rExtract function
Extract output lines from an R command.
The supplied txt
is expected to be stdout from the R console and pat
is usually an R command to search for. Find the most recent instance of the
command and return its output.
Implementation
String rExtract(String txt, String pat) {
// Split the string into lines.
List<String> lines = txt.split('\n');
List<String> result = [];
// Initialize with a value that indicates no start index found.
int startIndex = -1;
// Starting from the end of the supplied [txt], often being the [stdout] from
// the R console, find the most recent instance of [pat]
for (int i = lines.length - 1; i >= 0; i--) {
if (lines[i].contains(pat)) {
startIndex = i;
break;
}
}
if (startIndex != -1) {
for (int i = startIndex + 1; i < lines.length; i++) {
if (lines[i].startsWith('>')) {
// Found the next line starting with '>'. Stop adding lines to the
// result.
break;
}
result.add(lines[i]);
}
}
// Join the lines.
String content = result.join('\n');
// Clean the result.
content = cleanString(content);
return content;
}