开发者

Limit length of characters in a regular expression

开发者 https://www.devze.com 2022-12-26 16:38 出处:网络
Is there a way to limit a regular expression to 100 characters with a regular expression? \\[size=(.*?)\\](.*?)\\[\\/size]

Is there a way to limit a regular expression to 100 characters with a regular expression?

\[size=(.*?)\](.*?)\[\/size]

So Look at me! wouldn't work.

I want to limit the numbers, only allow numbers between 开发者_JAVA百科1 and 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.


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:

  1. ^ = start of input
  2. () = multiple options to match
  3. First argument [1-9] - matches any entries between 1 and 9
  4. | = OR argument separator
  5. Second Argument [1-9][0-9] - matches entries between 10 and 99
  6. Last Argument 100 - Self explanatory - matches entries of 100

This will not accept:

  1. Zero - 0
  2. Any integer preceded with a zero - 01, 021, 001
  3. Any integer greater than 100


If you want numbers from 1 up to 100:

100|[1-9]\d?


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}$'


(^(\d{2})|^(\d{4})|^(\d{5}))$

This expression takes the number of length 2,4 and 5. Valid Inputs are 12 1234 12345

0

精彩评论

暂无评论...
验证码 换一张
取 消