2

I need to write a regex that checks if a phrase contains a positive number. I have found this:

[1-9]\d* (left|remaining).*$

But it does not work on negative numbers. So I want to check if the words "left" or "remaining" follows a positive number. These are the test cases

0 left
1 left
2 left
3 left
0 remaining
1 remaining
2 remaining
you have 3 left
(13 left)
there are 12 remaining today
You have (-12 left) today
There are (3 left)
-15 remaining today
you have -24 left today
Leoid9
  • 91
  • 3

1 Answers1

2

Use

(?<!-)\b[1-9]\d*\s+(left|remaining)

See proof.

Explanation

--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    -                        '-'
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  [1-9]                    any character of: '1' to '9'
--------------------------------------------------------------------------------
  \d*                      digits (0-9) (0 or more times (matching
                           the most amount possible))
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    left                     'left'
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    remaining                'remaining'
--------------------------------------------------------------------------------
  )                        end of \1
Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37