0

I have a string with a value that ranges from any negative number to any positive number. I only want to match on the absolute value of that number equal to or greater than 120.

Ex. I have -843 I need to know if that number is greater than 120.
Ex. I have 1002 I need to know if that number is greater than 120.
Ex. I have 22, no match.
Ex. I have -119, no match.

I started working this but got stuck after 3 digits. The number can be any number.

.*([1-9][2-9]\d)$

https://regex101.com/r/SU6Znr/1

Mistalis
  • 17,793
  • 13
  • 73
  • 97
Brandon Wilson
  • 4,462
  • 7
  • 60
  • 90

2 Answers2

4

Here is a suggestion:

^(-?(?:1[2-9]\d|[2-9]\d\d|[1-9]\d{3,}))$

Explanation

  • ^ start of the string
  • -? in order to accept negative values
  • 1[2-9]\d any value between 120 and 199
  • [2-9]\d\d any value between 200 and 999
  • [1-9]\d{3,} any 4+ digits number starting with 1
  • $ end of the string

Test it on regex101

Community
  • 1
  • 1
Mistalis
  • 17,793
  • 13
  • 73
  • 97
-1

You'll need to use 2 cases in your regex: one for when the number is exactly three digits, and one for when the number is more than three digits. You'll want to remove the .* at the beginning of the regex because it matches anything, including non-digits.

You can use:

^(-|)([1-9][2-9]\d|[1-9]\d{3,})$

The regex has beginning/ending anchors to make sure you're checking the entire string. The first OR condition checks for a negative sign. Assuming there are no leading zeros, [1-9][2-9]\d checks for a 3 digit number greater than or equal to 120, and [1-9]\d{3,} checks for a number at least 4 digits long.

EDIT:

My regex failed to validate some three digit numbers, such as 200. The best regex is the one accepted above:

^(-?(?:1[2-9]\d|[2-9]\d\d|[1-9]\d{3,}))$

Ryan M
  • 101
  • 2
  • 11
  • This will reject `200` and many other valid numbers. Also, an optional minus sign should be matched using `-?`, not with alternation. – Tim Pietzcker Jun 27 '17 at 15:07
  • @TimPietzcker you're right, that case went over my head. I edited my answer to include the accepted regex, so that my answer doesn't remain incorrect (although I left the incorrect regex to see my train of thought). I appreciate the comment! – Ryan M Jun 27 '17 at 17:18