javascript – What’s the regex pattern that comma separates a number’s integer part every 3 digits and not the decimal part?
You can replace (zero-width) matches of the following regular expression with a comma:
\B(?:(?=(?:\d{3})+\.)|(?!.*\.)(?<!\..*)(?=(?:\d{3})+$))
This expression can be broken down as follows.
\B # match a non-word boundary
(?: # begin a non-capture group
(?= # begin a positive lookahead
(?: # begin a non-capture group
\d{3} # match 3 digits
) # end non-capture group
+ # execute preceding non-capture group >= 1 times
\. # match '.'
) # end positive lookahead
| # or
(?! # begin a negative lookahead
.*\. # match >= 0 chars other than line terms then '.'
) # end negative lookahead
(?<! # begin a negative lookbehind
\..* # match '.' then >= 0 chars other than line terms
) # end negative lookbehind
(?= # begin a positive lookahead
(?: # begin a non-capture group
\d{3} # match 3 digits
) # end non-capture group
+ # execute preceding non-capture group >= 1 times
$ # match end of string
) # end positive lookahead
) # end non-capture group
Notice that the first part of the alternation matches string representations of numbers with a decimal point. That way the relatively expensive negative lookbehind ((?<!\..*)) need not be executed when the string contains a decimal point.
Read more here: Source link
