Search code examples
regexnegate

Negating Regular Expression for Price


I have a regular expression for matching price where decimals are optional like so,

/[0-9]+(\.[0-9]{1,2})?/

Now what I would like to do is get the inverse of the expression, but having trouble doing so. I came up with something simple like,

/[^0-9.]/g

But this allows for multiple '.' characters and more than 2 numbers after the decimal. I am using jQuery replace function on blur to correct an input price field. So if a user types in something like,

"S$4sd3.24151 . x45 blah blah text blah" or "!#%!$43.24.234asdf blah blah text blah"

it will return

43.24

Can anyone offer any suggestions for doing this?


Solution

  • I would do it in two steps. First delete any non-digit and non-dot-character with nothing.

    /[^0-9.]//g
    

    This will yield 43.24151.45 and 43.24.234 for the first and second example respectively. Then you can use your first regex to match the first occurence of a valid price.

    /\d(\.\d{1,2})?/
    

    Doing this will give you 43.24 for both examples.