PHP Developers Network
http://forums.devnetwork.net/

Regex min/max length combined with other expressions
http://forums.devnetwork.net/viewtopic.php?f=38&t=141841
Page 1 of 1

Author:  xanuex [ Thu Oct 01, 2015 2:17 am ]
Post subject:  Regex min/max length combined with other expressions

I'm working on a Regex which has the following limitations;

1. No punctuations but a dash
2. No numbers only characters
3. First letter should be uppercase

4. Minimal 3 characters
5. Maximal 12 characters

Except for nr. 4/5 this has the required result.
^[A-Z][a-z]+(-[A-Z][a-z]+)?$


For the last part I've tried the following but it's not working correctly. Who can help me figure this out?
^([A-Z][a-z]+(-[A-Z][a-z]+)?){2,12}$

See also
https://www.debuggex.com/r/JIyOwvdYdO0WgrwI

Author:  requinix [ Thu Oct 01, 2015 2:45 am ]
Post subject:  Re: Regex min/max length combined with other expressions

If you only had one part with a quantifier (+) then it would be easy: it's 3-12 minus the number of required characters. I think that's what you were trying to go for, but (1) it doesn't account for how the first [a-z]+ has an unknown length and (2) the {2,12} will try to repeat the entire expression.

If you absolutely must use a regular expression for it, use a positive lookahead at the beginning of the string.
Code:
^(?=.{3,12}$)[A-Z][a-z]+(-[A-Z][a-z]+)?$

"At this point there must be 3-12 characters and then the end of the string". The rest of the regex deals with the character restrictions.

Naturally, if you do not absolutely need a regular expression then strlen() is the way to go.

Author:  xanuex [ Thu Oct 01, 2015 7:32 am ]
Post subject:  Re: Regex min/max length combined with other expressions

I've had it working with one part indeed but it is a regex for first names which can only maintain a dash and need to start with a capital like Susy-Lue.

The expression provided seems to work perfectly, thanks!!

Page 1 of 1 All times are UTC - 5 hours
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/