1

I have an input string that is a percentage value, i.e. "40%*", "90%*", etc. I wrote a regular expression to capture just the number so I can convert it to a number and do math on it (comparisons). For this I used the following regular expression, which worked fine for this type of input:

'40%*'.match(/[^%]*/)[0] // Outputs '40'

However, sometimes the input will look like this: "<10%*". Because of this edge case, my regular expression has a bug. In order to fix, I tried this:

'<10%*'.match(/[^[%<]]*/)[0] // Outputs '1'

But now it will only capture the "1" on a str.match, instead of the full "10". I am not sure why it seems like the * operator to match 0 or more characters seems to only be matching 1 character here?

Jackson Lenhart
  • 630
  • 3
  • 7
  • 19
  • 3
    If these are the only possible input formats, a simple `/\d+/` works. – ASDFGerte Feb 17 '20 at 16:03
  • 1
    Just [have a look at what your regex does](https://regex101.com/r/H0ib9R/1). Use the well-known `s.match(/\d+/)` or `s.match(/\d*\.?\d+/)` to extract the first number from a string – Wiktor Stribiżew Feb 17 '20 at 16:04

0 Answers0