tags:

views:

291

answers:

2

Is there a way to limit a regex to 100 characters WITH regex?

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

So [size=500]Look at me![/size] wouldnt work.

I want to limit the numbers, only allow numbers between 1 and 100

+2  A: 

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.

John Feminella
thanks and would anyone mind telling me, as im a complete noob, where in my regex i should put this? i tried `'/\[size=(.*?)\d{1,100}](.*?)\[\/size]/i'`
Jorm
@Jorm: I'm not sure that your comment really solves the problem - this would allow a sequence of digits between 1 and 100 digits long, not values in the range "1" to "100".
GalacticCowboy
@Jorm: Don't use regular expressions to validate numeric ranges. It's too error-prone. (See above.) Instead just extract the value from `size` with the first regex, then check to see if the second regex's extracted value violates the `size` parameter.
John Feminella
+2  A: 

If you want numbers from 1 up to 100:

100|[1-9]\d?
Kobi