简体   繁体   中英

How to match a whole string that contains just two and no more than two digits between 0 and 10 in regex?

This regex does not work for me as selects all groups of two and multiple digits and not the string.

abcde9 = match
abcde12 = not matched
abcde12345678 = not matched

What I have at the moment is this, it I just can't include the 0 and the 10 as two digits numbers in the regex, can anyone help me?

\d{0,10}[1-9]

Is that what you looking for:

/(0[1-9])$/

You can test that regex to make sure it fits your needs: https://regex101.com/r/hX6lB7/3

I think you are looking for

^\D*(?:[0-9]|10)(?:\D+(?:[0-9]|10))?\D*$

See demo

This will match a whole string that contains 1 or 2 whole integer numbers from 0 to 10, and no other digits.

The regex breakdown:

  • ^ - start of string
  • \\D* - 0 or more characters other than digit
  • (?:[0-9]|10) - numbers from 0 to 10
  • (?:\\D+(?:[0-9]|10))? - 1 or 0 occurrence of
    • \\D+ - 1 or more characters other than digit
    • (?:[0-9]|10) - numbers from 0 to 10
  • \\D* - 0 or more characters other than digit
  • $ - end of string

If you want to match any string containing exactly one integer from 0 to 10 then use

^\D*(\d|10)\D*$

which means "any non-digit content followed by either a single digit or the number 10 and then followed by any non-digit content"

try it at regex101

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM