How do I add thousand separators with reg ex?

跟風遠走 提交于 2019-12-10 18:43:56

问题


I'm using this free RegExp Designer which does find and replace. How do I search for all numbers and add thousand separators?

Input:      <node num='12345678'>
Output:     <node num='12,345,678'>

回答1:


To reformat numbers only in "num" attribute values you can do this:

(?<=num='\d+)(?=(?:\d{3})+(?!\d))

But note that this will only work in .NET regexes, which is what RegExp Designer uses. Most regex flavors only allow lookbehinds that match a fixed number of characters. Java regexes allow variable-length lookbehinds as long as there's an obvious maximum length, so you can fake it out by using {min,max} quantifier an arbitrary number for the maximum:

(?<=num='\d{1,20})(?=(?:\d{3})+(?!\d))

John Hyland's regex will work in any flavor that supports lookbehinds.

EDIT: I almost forgot; here's how you can do it without lookbehinds:

(num='\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))

I like this one best for purely aesthetic reasons. :)

EDIT2: I forgot to mention that the replacement string for the last one is "$1,"




回答2:


s/(?<=\d)(?=(\d\d\d)+(?!\d))/,/g

That said, if you're working with this data as anything other than strings at some point, whatever language you're working in probably has facilities for formatting numeric output.



来源:https://stackoverflow.com/questions/1228129/how-do-i-add-thousand-separators-with-reg-ex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!