-3

The following are valid numbers for various financial displays depending on the region, etc:

1,000
1000.00
1,000,000.00
2.000.000,00
123748 # without commas
4 294 967 295,000
0.24
.24
24
24.

What would be a better approach to finding a regex for the above, doing one large regex or multiple regexes for each pattern? For example, an individual pattern being like:

no_thousands_separator = '\d+[.,]?\d{0,3}?
carl.hiass
  • 1,526
  • 1
  • 6
  • 26
  • Wat exactly do you want to match? Should `4 294 967 295,000` be a whole match? Is this the only value that you want to match or could it also be part of a larger text? – The fourth bird Oct 28 '19 at 21:06
  • This is probably too complicated of a problem for regex to handle alone, if you want to cover all your bases. Take a look at the answers here https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-currency-string-in-javascript and maybe consider using something like this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat – CAustin Oct 28 '19 at 21:10
  • Some answers can be found at https://stackoverflow.com/questions/20157375/fuzzy-smart-number-parsing-in-python – marcmagransdeabril Oct 28 '19 at 23:19

3 Answers3

1

You can make one regex, to keep things more simple:

\d*(?:([., ])(?:\d{3}\1)*\d{3})?(?:[.,]\d*)?

Inspect on regex101.com

How does this work?

\d*          Where numbers can occur
([., ])?     Capture the thousands separator
\d{3}        Match 3 digits between separators
\1           Recall thousands separator
(?:[.,]\d*)? Optionally capures decimal part (no thousands separator allowed here)
FZs
  • 16,581
  • 13
  • 41
  • 50
1

You likely want to design some expression, not exactly, but maybe similar to,

^\.?(?:(?:\d{1,3}[,. ])*\d{1,3}(?:\.\d{2})?|\d+\.\d+|\d+)\.?$

One way to design that is to look for your most complicated pattern, write an expression, alter, then continue to your simplest pattern.

Demo

I've just added two \.? in the beginning and end of the expression, but that's not really right, you are going to incorporate those wherever you want to.


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

This expression would not validate, but only pass those numbers.

Community
  • 1
  • 1
Emma
  • 27,428
  • 11
  • 44
  • 69
0

Play with regex below:

function parseNum(str) {
   const match = /^[\d.,\s]+$/.exec(str);

   return match ? match[0] : null;
}
zemil
  • 3,235
  • 2
  • 24
  • 33