Java – Regular expression for two possible character counts

Regular expression for two possible character counts… here is a solution to the problem.

Regular expression for two possible character counts

I need a regular expression to allow two different character counts.
I only want to allow strings that are 5 or 7 characters in length but not any value in between.

For example: for 5 and 7

asdfg = ok
asdfgh = fail
asdfghj = ok

Thanks!

Solution

You can use this regular expression:

^.{ 5}(?:.{ 2})?$

RegEx Demo

Related Problems and Solutions