toSnakeCaseAcronyms method
Converts to snake_case, lowercasing acronyms (e.g. HTTPResponse → http_response).
Returns the snake_case string.
Example:
'HTTPResponse'.toSnakeCaseAcronyms(); // 'http_response'
Implementation
@useResult
String toSnakeCaseAcronyms() {
if (isEmpty) return this;
final StringBuffer sb = StringBuffer();
for (int i = 0; i < length; i++) {
final String c = this[i];
if (c == ' ' || c == '-') {
sb.write('_');
} else {
final bool upper = c.toUpperCase() == c && c.toLowerCase() != c;
if (upper && i > 0) {
final String prev = this[i - 1];
final bool prevLower = prev.toUpperCase() != prev || prev.toLowerCase() == prev;
final bool nextLower = i + 1 < length && this[i + 1].toLowerCase() == this[i + 1];
if (prevLower || (prev.toUpperCase() == prev && nextLower)) sb.write('_');
}
sb.write(c.toLowerCase());
}
}
return sb.toString().replaceAll(RegExp(r'_+'), '_').replaceAll(RegExp(r'^_|_$'), '');
}