Patidati
Patidati

Reputation: 1088

Regular expression: Define max length of string, with repeated groups

The title might be confusing, but I will try to use some examples to explain. This is the current expression I've made.

^([A-ZÆØÅ][a-zæøå]+[\s-]{1}){2,20}$

I want an expression that will match these: So the general rule is,

-Every word has to start with a capital letter

-Following a capital letter can only be small letters

-There can be max one - or whitespace after each other

And the hard part, in every combination of these, I want the final line to be a maximum of 20 chars

I want an expression that will match these:

April-Can Æøå
An-An-An An An-An
Aaaaabbbbbcccccddddd
Aaa

Non-matching

andkas
Andfak-lkakad
AppleApple
Carrotcarrotcarrotcarrotcarrotcarrot
Banana- Banana
Apple-apple-apple-apple-apple banana banana apple carrot

Upvotes: 4

Views: 4659

Answers (2)

anubhava
anubhava

Reputation: 784958

You can use this regex:

^([A-ZÆØÅ][a-zæøå]{1,19}[\s-])*[A-ZÆØÅ][a-zæøå]{1,19}$

RegEx Demo

Upvotes: 0

Toto
Toto

Reputation: 91375

Use lookahead:

^(?=.{2,20}$)[A-ZÆØÅ][a-zæøå]+(?:[\s-][A-ZÆØÅ][a-zæøå]+)*$

Where:

(?=.{2,20}$) makes sure you have 2 to 20 char in tyhe string.
then you have a word that starts with capital letter eventually followed by a space or a dash and another word. It may have several words

Upvotes: 14

Related Questions