Regex min/max length combined with other expressions

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

xanuex
Forum Newbie
Posts: 2
Joined: Thu Oct 01, 2015 2:15 am

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

https://www.debuggex.com/r/JIyOwvdYdO0WgrwI
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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: 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.
xanuex
Forum Newbie
Posts: 2
Joined: Thu Oct 01, 2015 2:15 am

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!!