Kev
Kev

Reputation: 2716

Regex to match optional character in any order

I need to be able to match strings like:

GQG6VJ6K, TYTU-TIDM-56, 4-5-P-Z, etc.

The hyphen - is optional, but there must be at least one alphanumeric character.

So far the best attempt I have come up with is [A-Z0-9-]+ which wrongly matches a single hyphen.

I also tried (?[-]*)(?[A-Z0-9]+) but it doesn't work (I'm a regex noob). Bonus points for why.

What's the solution?

EDIT:

@archeong87 led me to my final solution: ^[A-Z0-9]+(-{0,1}[A-Z0-9]+)*$

Upvotes: 0

Views: 5926

Answers (4)

xdazz
xdazz

Reputation: 160843

Use:

/^(?=.*[a-z\d])[a-z\d-]*$/i

i means case insensitive, if you only want upper case, then

/^(?=.*[A-Z\d])[A-Z\d-]*$/

Upvotes: 0

Andrew Cheong
Andrew Cheong

Reputation: 30273

You were pretty close!

^(?=.*[A-Z0-9])[A-Z0-9-]+$
||             |         |
||             |         anchor your regex
||             |
||             what you were already doing
||
|lookahead assertion: at least 1 alphanumeric
|
anchor your regex

EDIT:

While thinking about how to exclude - being at the beginning or the end, I realized there was a much simpler solution:

^[A-Z0-9]+(-[A-Z0-9]+)*$

It looks like @AndreKR had this idea, so +1 to him.

Upvotes: 0

Ωmega
Ωmega

Reputation: 43673

Use regex pattern

^[A-Z0-9-]*[A-Z0-9][A-Z0-9-]*$
 └───┬───┘ └───┬──┘└───┬───┘
     │         │       └ alphanumeric characters or hyphens (none or any)
     │         │
     │         └ one alphanumeric character
     │
     └ alphanumeric characters or hyphens (none or any)

or

^(?=[A-Z0-9-]*$).*[^-]
    └───┬───┘     └─┬┘
        │           └ non-hyphen
        │
        └ allowed characters

Upvotes: 1

AndreKR
AndreKR

Reputation: 33678

This should do the trick:

([A-Z0-9]-?)*[A-Z0-9]

Upvotes: 2

Related Questions