with the help of this thread I have tweak a regex for my use. Decimal number regular expression, where digit after decimal is optional
So far I have this /^-?[1-9]$|^,\d $|^0,\d$|^[1-9]\d*,\d*$
It works for
- -12
- 0
- 1
It does not work for
- -1,
- -1,1
what I want is:
- -1,1
may a kind soul explain what I am missing or doing wrong with this regex pls? Thank you very much! I am tweaking it with : https://regexr.com/6sjkh but it's been 2 hours and I still don't know what I am missing. I don't know if language is important but I am in visual basic.
CodePudding user response:
The thread you are quoting in your question has already some good answers. However if you do not need to also capture and do not care about numbers without the leading zero before the comma and no thousand separator I would recommend the following:
/^-?\d (,\d )?/
- The ^ indicates the beginning so that no other text in front is allowed
- The -? is allowing a negative sign ( you need to escape this with \ as - can be a special character
- \d expects 1 or more digits
- The last part in parentheses covers the fractional part which as a whole can occure 0 or one time due to the question mark at the end
- , is the decimal separator (if you want to have dots you need to put her ., as a dot is the special character for any character and also needs to be escaped if you look for a real dot)
- \d is again one or more digits after the comma
I hope this helps a bit. Besides this I can also recommend using an online regular expression tool like https://regex101.com/