Regex to validate currency, fractional, accepting negatives

0

I will use it in Delphi 10.1. I was able to reach the expression below, but for lack of knowledge and practice, I'm not getting as far as I want.

Regex:

^(^[\-]?[1-9]|0)(?:[0-9]{0,10}|0)(?:,\d{0,2})?$



I need to analyze whether the number is a valid monetary value, that is just numbers, no space, no thousand separator or currency symbol, has none, one or even two decimal places, and that I accept positive (minus sign) and negative (preceded by -), accepting zero if it is the only number, but not zero at the beginning if it is integer or fractional, but accepts zero at the beginning if the zero is the only one previous to the comma and the fractional part is greater than one cent.

You should accept:

0
0,//Será formatado após
0,0
0,00
0,01 até 0,99
0,1
1234567890,99
-1234567890,99
-0,01 até -0,99
1,00
-1,00



You can not accept:

-0
-0,
-0,00
-,01 a -,99
//Sequencia vazio
01,00
01
0012
    
asked by anonymous 17.07.2018 / 14:54

1 answer

0

There are 3 rules you should consider with your problem:

  • Can not capture if it is negative and start at ",";
  • Can not catch if number is started at "0" and does not have "," then;
  • You can not capture a negative number that does not have at least a number from 1 to 9 in character sequence.

So to cover all possibilities should be captured only

  • Positive numbers that start at 0 and have decimals immediately after 0;
  • Negatives that start at 0, but have at least a number between 1 and 9 in the character sequence (indicating that it is not only a negative 0);
  • Numbers that start between 1 and 9 and can contain decimal parts;
  • negative numbers starting at 1 or 9 that may or may not contain decimal places;
  • Number 0 that does not have the character "-" before but may contain a character "," after "0"; then;

For this I made this regex:

(?<!-)(0,\d*[0-9])|(?<!0)([1-9]\d*,\d*)|(-[0-9],\d*?[1-9]\d*)|(-[1-9]\d*,{0,1}\d*)|\b(?<!-)(0)[a-zA-Z,\n]

Each capture group represents one of these possibilities.
You can see this regex running and its result in this link .

    
26.07.2018 / 04:33