简体   繁体   English

用千位分隔符装饰字符串中的数字

[英]Decorating numbers inside the string with the thousand separator

A have a string that contains one ore more number. 包含一个或多个数字的字符串。 The numbers are normally integers, but also decimal could be expected at some point. 这些数字通常是整数,但在某些时候也可以期望是十进制。 I looking for a solution that adds the thousand separator(. or ,) to all numbers inside the string. 我正在寻找一种将千位分隔符(。或,)添加到字符串中所有数字的解决方案。

For example 例如

  1. 100000 -> ?100,000? 100000->?100,000?
  2. ?100000?50000 -> ?100,000?50,000 ?100000?50000->?100,000?50,000
  3. X10000.5? X10000.5? -> X100,00.5? -> X100,00.5?

Any idea? 任何想法?

A hacky solution in pure regex is to replace all occurences of 纯正则表达式的一个hacky解决方案是替换所有出现的

(?<=\d)(\d{3})(?!\d)

with ,$1 . ,$1 This is, of course, very limited, as it only adds one separator per number, and also adds separators after a comma. 当然,这是非常有限的,因为每个数字只添加一个分隔符,并且在逗号后也添加分隔符。 See regex101 demo. 请参阅regex101演示。


A far cleaner solution is to search for numbers using a regex such as \\d+(?:\\.\\d+)? 一个更简洁的解决方案是使用正则表达式(例如\\d+(?:\\.\\d+)?搜索数字\\d+(?:\\.\\d+)? , convert each match to a number, and re-insert the formatted number into the text. ,将每个匹配项转换为一个数字,然后将格式化后的数字重新插入文本中。

(You'll have to forgive me for not including any code, but I haven't coded in C# in ages.) (您必须原谅我不包含任何代码,但是我已经很久没有使用C#了。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM