问题
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