Zip code and country match with Javascript

I have some difficulties to run regex for these cases - sorry, I'm very new to regex and can't figure it out.

The sample looks like this:

  • 12 (true)
  • 123 (true)
  • 1234 (true)
  • 12345 (true)
  • 1 a ... (false)
  • 12 a ... (false)
  • 123 a ... (false)
  • 1234 a ... (false)
  • 12345 m (true)
  • 12345 mün (true)
  • münchen 123 (false)
  • mün 12345 (true)

therefore, if combined with the letters, the zip code must fill in the maximum length specified in the range eg {2,5} .

I tried with this, but it does not work as I need it:

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

+4
source share
2 answers

It works:

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

Pay attention to the OR operator:

Corresponds to [0-9]{5}\s[az]+ OR [az]+\s[0-9]{5} OR [0-9]{2,5}

You can add any international characters to the word match, for example: [a-zä-üß] , but depending on the language you use, the best options may be supported.

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

+2
source

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}/ } 
+3
source

Source: https://habr.com/ru/post/1500010/


All Articles