Skip to content

Instantly share code, notes, and snippets.

@viztushar
Created June 15, 2022 11:19
Show Gist options
  • Save viztushar/ab26b288b7ab10f6c15c4dfb5a173331 to your computer and use it in GitHub Desktop.
Save viztushar/ab26b288b7ab10f6c15c4dfb5a173331 to your computer and use it in GitHub Desktop.
int? parseIntPrefix(String s) {
var re = RegExp(r'(-?[0-9]+).*');
var match = re.firstMatch(s);
if (match == null) {
return null;
}
return int.parse(match.group(1)!);
}
int compareIntPrefixes(String a, String b) {
var aValue = parseIntPrefix(a);
var bValue = parseIntPrefix(b);
if (aValue != null && bValue != null) {
return aValue - bValue;
}
if (aValue == null && bValue == null) {
// If neither string has an integer prefix, sort the strings lexically.
return a.compareTo(b);
}
// Sort strings with integer prefixes before strings without.
if (aValue == null) {
return 1;
} else {
return -1;
}
}
void main() {
List<String> hi = ['1','3c','2','1c','3a','bca','a','11','2','3','4','7','5','6'];
hi.sort();
print(hi);
hi.sort(compareIntPrefixes);
print(hi);
hi.sort();
print(hi);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment