magic.77
magic.77

Reputation: 917

Postcode and Country Match with Javascript

I have some difficulties to get a regex running for these cases - sorry I´m very new to regex and can´t figure it out.

The pattern looks like this:

so if combined with letters, postcode has to fullfill the max length given in the range like {2,5}.

I tried with this one, but is doesn´t work like I need it:

/^([0-9]{2,5})(\s+[^a-zA-Z]{2,})?$/

Upvotes: 4

Views: 166

Answers (2)

Pedro L.
Pedro L.

Reputation: 7536

This works:

/^([0-9]{5}\s[a-z]+)$|^([a-z]+\s[0-9]{5})$|^([0-9]{2,5})$/i (edited after comment)

Note the OR operator:

Matches [0-9]{5}\s[a-z]+ OR [a-z]+\s[0-9]{5} OR [0-9]{2,5}

You can add any international characters in the word match, for example: [a-zä-üß] but depending on the language you are using, better options could be supported.

TESTS http://jsfiddle.net/zd4Qm/4/

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 992917

Sometimes, regular expressions are not the only answer.

if (there are letters in the string) {
    search for /\d{5}/
} else {
    search for /\d{2,5}/
}

Upvotes: 3

Related Questions