-1

I am trying to match decimals for both strings and floats. Noticed that the below RegEx matches floats ending with a period(.) as well which isn't expected.

const regex = RegExp("^(\\d*\\.)?\\d+$");
arrTest = ["3.", 3., "4.", 4., "5.5", 5.5];

arrTest.forEach(element => {
    console.log(regex.test(element)) 
});
/*
Result
=======
"3."  - False
 3.   - True (Expecting false since regex should end with a number)
"4."  - False
 4.   - True (Expecting false since regex should end with a number)
"5.5" - True
 5.5  - True
*/
Titus
  • 22,031
  • 1
  • 23
  • 33
brigzz
  • 9
  • 1
  • 1
  • `\\d*\\.` - you allow any amount of digits before the dot, including no digits. Just use `+` for one or more and make the dot and rest of the digits optional. – VLAZ Apr 28 '20 at 14:00
  • 1
    `3.` is evaluated to `"3"` and it matches your regex. – Wiktor Stribiżew Apr 28 '20 at 14:01
  • Does this answer your question? [Regular expression for floating point numbers](https://stackoverflow.com/questions/12643009/regular-expression-for-floating-point-numbers) – VLAZ Apr 28 '20 at 14:02
  • Also look at [this article](https://www.regular-expressions.info/floatingpoint.html) on regular expressions for floating point numbers. – VLAZ Apr 28 '20 at 14:03
  • Change `console.log(regex.test(element))` with `console.log(element + ': ' + regex.test(element))` and analyse the output. – Toto Apr 28 '20 at 14:04

1 Answers1

0

3. is 3.

RegExp pattern matching uses strings. Anything you pass will be first converted to a string. You cannot write 3. in your JavaScript code and not have that evaluate to the number 3, and therefore become "3" when converted to a string.

Lee Kowalkowski
  • 11,591
  • 3
  • 40
  • 46