Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Minimum Length

Tags:

regex

This will eventually be part of a larger expression but I've reduced it down to a much simpler form here (ie, there will be a true possibility of 40 characters instead of the 19 possible here). Given the following input:

;123?T

I get a successful match against this regex:

^(?:;(\d{0,19})\?.){1,40}$

However, I do not get a match against this regex:

^(?:;(\d{0,19})\?.){3,40}$

The only thing I'm changing is the minimum length, both of which the input should satisfy. Why does the first one find a match and the second one doesn't? Maybe I'm just not understanding this quantifier but I thought it was simply {MIN, MAX}.

Also, I have tested this in both of the following online testers:

regular-expressions.info

regexpal.com

like image 623
heath Avatar asked Jun 13 '13 21:06

heath


People also ask

How do you restrict the length of a regular expression?

The ‹ ^ › and ‹ $ › anchors ensure that the regex matches the entire subject string; otherwise, it could match 10 characters within longer text. The ‹ [A-Z] › character class matches any single uppercase character from A to Z, and the interval quantifier ‹ {1,10} › repeats the character class from 1 to 10 times.

What are all the limitations of using regular expressions?

Regexs can only parse regular grammers anything context-free and higher you need a stack (i.e. a real parser). That is their only real limitation, performance depends the particular implementation, but generally is slow even precompiled compared to a state machine.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.


1 Answers

With the first part of the expression ^(?:;(\d{0,19})\?.) you are matching all of this ;123?T.

With the next part of the expression {1,40} you are saying match the above 1 through 40 times. Notice that if you try to match ;123?T 3 times in a row, this obviously will not work, and that is the case when you say {3,40}.

like image 150
greedybuddha Avatar answered Oct 08 '22 15:10

greedybuddha