-1

I get an input for a town name and postal code.

I want to check if this input is in the correct format (specified below). Checking if the town exists is not needed.


I wanted to use a RegEx (Regular Expression) to check it, but I couldn't find a correct solution.


Valid Input Formats:

<Town Name> <Post Code>
<Town Name>, <Post Code>

Example Inputs:

Hamburg, 22850
Cambridge 44922

I want to check if the letters and the numbers are separated by a space (with an optional comma straight after the town name).

Helen
  • 185
  • 11
DataCent
  • 39
  • 8
  • If you are simply looking for the postal code, then this should be all you need: `(\d{5})$` – K.Dᴀᴠɪs Aug 28 '18 at 00:07
  • @K.Dᴀᴠɪs exactly but i want to check the town name in combination with a comma and the postal code. every part itself isn't a problem ;) – DataCent Aug 28 '18 at 00:17
  • I was basing that response off your statement, _"Checking if the town exists is not needed."_ But you can use `([\w\s]+),?\s(\d{5})$`, which contains 2 capturing groups. `$1` will return the town, `$2` will return the postal code. [See it Live Here](https://regex101.com/r/2xzEtn/1) – K.Dᴀᴠɪs Aug 28 '18 at 00:19

1 Answers1

0

This is the RegEx that you are looking for:

^[A-Za-z]+,? [0-9]{5}$

Try it online!


Explanation

 [A-Za-z]+               Checks that the first bit is just letters from A to Z (case-insensitive).
          ,?             Allows for 0 or 1 comma(s)
            ␠           Checks whether there is a space
              [0-9]{5}   Checks whether the second half is only made up of 5 digits from 0 to 9
^                     $  Makes sure that the Town Name and Post Code is all that the string contains
Helen
  • 185
  • 11