user429620
user429620

Reputation:

regex: match multiple allowed lengths?

So I want to allow A-Z with a length of 8 or 12.

I tried:

^[a-z]{8|12}$

but that doesn't work. What's the correct solution? (without repeating)

Upvotes: 9

Views: 12406

Answers (4)

david
david

Reputation: 419

I'd suggest this solution:

^([a-z]{4}){2,3}$

It means that the group [a-z] of length 4 has to match either 2 (total length: 8) or 3 (total length: 12) times. This way the set of allowed characters has to be defined only once.

Upvotes: 12

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626709

You need to use alternation like this:

^([a-z]{8}|[a-z]{12})$

There is no other regex solution that would not involve repeating the [a-z] part. At least you do not have to repeat the ^ and $ anchors if you use a grouping construct.

Alternatively, you may use an optional group, but that is only good when your pattern is static. Actually, the difference is negligent (tested at regexhero):

enter image description here

Upvotes: 19

Aran-Fey
Aran-Fey

Reputation: 43136

As an alternative to the "exactly 8 or exactly 12" types of patterns, here's an "8 and maybe 4 more" type pattern:

^[a-z]{8}([a-z]{4})?$

Upvotes: 9

sameera sy
sameera sy

Reputation: 1718

Try this

^[a-z]{8}$|^[a-z]{12}$

The multiple length field option isn't there, you have to give them out separately including the regex

Upvotes: 0

Related Questions