加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – 如何将逗号添加到字符串数字

发布时间:2020-12-14 06:01:13 所属栏目:百科 来源:网络整理
导读:我正在努力适应这个: Insert commas into number string 在飞镖工作,但没有运气. 其中一个不起作用: print("1000200".replaceAllMapped(new RegExp(r'/(d)(?=(d{3})+$)'),(match m) = "${m},"));print("1000300".replaceAll(new RegExp(r'/d{1,3}(?=(d
我正在努力适应这个:
Insert commas into number string
在飞镖工作,但没有运气.

其中一个不起作用:

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,"));

是否有更简单/有效的方法将逗号添加到字符串数字?

解决方法

你只是忘了把第一个数字变成组.使用这个短的:

'12345kWh'.replaceAllMapped(new RegExp(r'(d{1,3})(?=(d{3})+(?!d))'),(Match m) => '${m[1]},')

看看可读的版本.在表达式的最后部分,我添加了对任何非数字字符的检查,包括字符串结束,因此您也可以使用’12瓦’.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读