Limit length of characters in a regular expression?
If you want numbers from 1 up to 100:
100|[1-9]\d?
If you want to restrict valid input to integer values between 1 and 100, this will do it:
^([1-9]|[1-9][0-9]|100)$
Explanation:
- ^ = start of input
- () = multiple options to match
- First argument [1-9] - matches any entries between 1 and 9
- | = OR argument separator
- Second Argument [1-9][0-9] - matches entries between 10 and 99
- Last Argument 100 - Self explanatory - matches entries of 100
This will not accept:
- Zero - 0
- Any integer preceded with a zero - 01, 021, 001
- Any integer greater than 100
Is there a way to limit a regex to 100 characters WITH regex?
Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:
- one to match the maximum length you'd like to use
- one which uses the previously extracted value to verify that its own match does not exceed the specified length
If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,
\d{3}-\d{3}-\d{4}
will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.
Likewise, you can set upper or lower limits:
\d{5,10}
means "at least 5, but not more than 10 digits".
Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.
Limit the length of characters in a regular expression:
^[a-z]{6,15}$'
Limit length of characters or numbers in a regular expression:
^[a-z | 0-9]{6,15}$'