Regular expression ecample for postal code

Below is the req expression to match 5 digits and then we put () and inside those braces we put - then 4 digits and a ? after the braces .This ? is very imp it means either 1 group of -1111 or 0 groups

So either 1 group 11111-1111 or 0 groups will hold true 1111

If we want to check for more than 1 groups like 2 groups or 3 groups like 11111-1111-1111 then we have to either use * or plus after the group

    String challenge11 = "11111";
    String challenge12 = "11111-1111";
   
  System.out.println(challenge11.matches("^\\d{5}(-\\d{4})?$"));

  System.out.println(challenge12.matches("^\\d{5}(-\\d{4})?$"));

 //As mentioned above if we are looking at more than one pattern of -1111 we can use a + at the end of the group

  String challenge13 = "11111-1111-1111-1111";

  System.out.println(challenge13.matches("^\\d{5}(-\\d{4})+$"));
Reg expression for canadian postal code would be like this

Any letter than digit then another letter

Then space or - although space or - is optional that's why we use ? i.e 0 or 1 spaces or 1 dash - and since it is 0 or 1 dash so what we are doing here is instead of putting then in brackets( -)? we are putting them in square brackets to satisfy the OR condition ,so [ -]?

And then we have a digit, then letter and digit again.

Code is below

  String regExpPostalCode = "^[A-za-z]\\d[A-za-z][ -]?\\d[A-za-z]\\d$";
  // We can check for different formats of postal codes to see if they satisfy above regular expression
  System.out.println("H3H 2P1".matches(regExpPostalCode));
  System.out.println("H3H-2P1".matches(regExpPostalCode));
  System.out.println("H3H_2P1".matches(regExpPostalCode));
   System.out.println("H3H2P1".matches(regExpPostalCode));
   System.out.println("33H 2P1".matches(regExpPostalCode));
   System.out.println("H3H 2Pp".matches(regExpPostalCode));
   System.out.println("h3H 2p1".matches(regExpPostalCode));
   System.out.println("h3h 2P1".matches(regExpPostalCode));
   System.out.println("h3h2p1".matches(regExpPostalCode));
   System.out.println("h3h-2p1".matches(regExpPostalCode));
   System.out.println("h3h_2p1".matches(regExpPostalCode));