我试图通过编写这个扩展来解决这个挑战,但如果有更好的解决方案或代码,我将不胜感激。
extension SubString on String {
String addSeparator({int? qty = 3, String? separator = ","}) {
assert(qty! >= 1, "[qty] value as the number separator must be positive!");
assert(
separator! != "", "[separator] value as the number separator must not be empty!");
String tempNum=this;
String sign="";
String decimal="";
if(RegExp(r'^[-+]?[0-9](d+.?d*|.d+)').hasMatch(this)){
if(this[0]=="+"||this[0]=="-"){
sign=this[0];
tempNum=this.substring(1);
}
if(tempNum.contains(".")){
decimal="."+tempNum.split(".")[1];
tempNum=tempNum.split(".")[0];
}
}
return sign+(tempNum.split('')
.reversed
.join()
.replaceAllMapped(
RegExp(r'(.{})(?!$)'.replaceAll('''{}''', '''{$qty}''')),
(m) => '${m[0]}${separator}')
.split('')
.reversed
.join())+decimal;
}
}
并像下面的代码一样使用它:
void main() {
String numberExample = "+4654654.23535";
print('numberExample: ${numberExample.addSeparator(qty: 3,separator: ",")}');
String ibanExample= "5674565544112211";
print('ibanExample: ${ibanExample.addSeparator(qty: 4,separator: "-")}');
}