Dart如何将逗号添加到字符串编号 [英] Dart how to add commas to a string number
本文介绍了Dart如何将逗号添加到字符串编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对此进行调整:将逗号插入数字字符串可以飞镖工作,但是没有运气.
I'm trying to adapt this: Insert commas into number string to work in dart, but no luck.
这两个都不起作用:
print("1000200".replaceAllMapped(new RegExp(r'/(\d)(?=(\d{3})+$)'), (match m) => "${m},"));
print("1000300".replaceAll(new RegExp(r'/\d{1,3}(?=(\d{3})+(?!\d))/g'), (match m) => "$m,"));
是否有更简单/可行的方式将逗号添加到字符串编号?
Is there a simpler/working way to add commas to a string number?
推荐答案
您只是忘记了将第一位数字分组.使用这个简短的例子:
You just forgot get first digits into group. Use this short one:
'12345kWh'.replaceAllMapped(new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), (Match m) => '${m[1]},')
查看可读版本.在表达式的最后一部分中,我添加了对任何非数字字符(包括字符串结尾)的检查,以便您也可以将其与"12瓦特"一起使用.
Look at the readable version. In last part of expression I added checking to any not digit char including string end so you can use it with '12 Watt' too.
RegExp reg = new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
Function mathFunc = (Match match) => '${match[1]},';
List<String> tests = [
'0',
'10',
'123',
'1230',
'12300',
'123040',
'12k',
'12 ',
];
tests.forEach((String test) {
String result = test.replaceAllMapped(reg, mathFunc);
print('$test -> $result');
});
它完美地工作:
0 -> 0
10 -> 10
123 -> 123
1230 -> 1,230
12300 -> 12,300
123040 -> 123,040
12k -> 12k
12 -> 12
这篇关于Dart如何将逗号添加到字符串编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文