senzacionale
senzacionale

Reputation: 20906

Regex for postcode with - allowed

This is my regex for postcodes

^[a-zA-Z0-9]{1,9}$

but A-12345 is not allowed. How to change the regex that - will be also allowed?

Upvotes: 0

Views: 50

Answers (2)

falsetru
falsetru

Reputation: 369044

Add - at the beginning or at the end of the character set ([...]):

^[-a-zA-Z0-9]{1,9}$

Why at the beginning or at the end?: If - is placed as the first or the last character, it will match - literally instead of matching range of characters.

Upvotes: 3

p.s.w.g
p.s.w.g

Reputation: 149010

Try this:

^[a-zA-Z0-9-]{1,9}$

This will match strings consisting of 1 to 9 Latin letters, decimal digits or hyphens. If you use the CASE_INSENSITIVE flag, you can simplify this to:

^[a-z0-9-]{1,9}$

Upvotes: 2

Related Questions