Home > Software design >  Regex for alphanumeric, but allow * or - zero or 1 times , while not exceeding max length
Regex for alphanumeric, but allow * or - zero or 1 times , while not exceeding max length

Time:11-16

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

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

CodePudding user response:

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:

  • Related