Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex for alphanumeric, but allow * or – zero or 1 times , while not exceeding max length

I want a regex pattern to match alphanumeric but only allow *(asterisk) or -(hyphen) to present no more than 1 time. Also, the string should not exceed the length of 5.

matched strings

abcds
a*a1a
11*a-
-a*hu
124ed
0-aur
ABC
8*-a
a

not matched string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

**ab1 <-- two *s
--ahy <-- two -s
0-a-* <-- two -s
111-*1  <--exceeds length
abcdef  <--exceeds length
u-a-r  <-- two -s

Appreciate any help!

>Solution :

You may use a negative Lookahead to confirm that the string doesn’t contain more than one of a given character. Here’s an example:

^(?:[A-Za-z0-9]|([*-])(?!.*\1)){1,5}$

Demo.

Or:

^(?!.*([*-]).*\1)[A-Za-z0-9*-]{1,5}$

Demo.


References:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading