Page 1 of 1

Regex min/max length combined with other expressions

Posted: Thu Oct 01, 2015 2:17 am
by xanuex
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

Re: Regex min/max length combined with other expressions

Posted: Thu Oct 01, 2015 2:45 am
by requinix
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: Select all

^(?=.{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.

Re: Regex min/max length combined with other expressions

Posted: Thu Oct 01, 2015 7:32 am
by xanuex
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!!