Home > Software design >  Match any number BUT positive 1-10
Match any number BUT positive 1-10

Time:12-12

I've tried the following without any success

^((\d{1,})\b[^1-10]\b)$

What should match: "11", "0", "-1", "100" and any number which is not 1-9

What shouldn't match: "10", "1", "abc11", "11abc", "a11b" and any number >= 1 AND <= 10

CodePudding user response:

It seems you want

^(?!(?:[1-9]|10)$)-?\d $

See the regex demo. Details:

  • ^ - start of string
  • (?!(?:[1-9]|10)$) - a negative lookahead that fails the match if there is a digit from 1 to 9 or 10 substring followed with end of string position immediately to the right of the current location
  • -? - an optional -
  • \d - one or more digits
  • $ - end of string.

If you cannot use lookarounds, you can use

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

See this regex demo. This regex matches:

  • ^ - start of string
  • ( - start of a capturing group:
    • -[0-9] | - - and then one or more digits, or
    • 0| - 0, or
    • 1[1-9]| - 1 and then a non-zero digit, or
    • [2-9][0-9]| - a digit from 2 to 9 and then any one digit, or
    • [0-9]{3,} - any three or more digits
  • ) - end of the group
  • $ - end of string

CodePudding user response:

This solution is not very elegant, but should match the data and rules you posted:

^((-1|0)|(\d{2,}))$  

Mini description of the parts of the expression:

  • ^ Start of string
  • (-1|0) the two "edge case" (Yes, hardcoded)
  • (\d{2,}) atleast two digits
  • $ end of string
  • (,) just grouping, to
  • Related