2

Below is the code I have written for a Canadian postal code validation script. It's supposed to read in a file:

123 4th Street, Toronto, Ontario, M1A 1A1
12456 Pine Way, Montreal, Quebec H9Z 9Z9
56 Winding Way, Thunder Bay, Ontario, D56 4A3
34 Cliff Drive, Bishop's Falls, Newfoundland B7E 4T

and output whether the phone number is valid or not. All of my postal codes are returning as invalid when postal codes 1, and 2 are valid and 3 and 4 are invalid.

import re

filename = input("Please enter the name of the file containing the input Canadian postal code: ")
fo = open(filename, "r")

for line in open(filename):

        regex = '^(?!.*[DFIOQU])[A-VXY][0-9][A-Z]●?[0-9][A-Z][0-9]$'
        m = re.match(regex, line)

        if m is not None:
                print("Valid: ", line)
        else: print("Invalid: ", line)

fo.close 
Vasili Syrakis
  • 9,321
  • 1
  • 39
  • 56
joeshmo
  • 21
  • 1
  • 3
  • possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – wallyk Apr 27 '15 at 22:19

2 Answers2

2

I do not guarantee that I fully understand the format, but this seems to work:

\b(?!.{0,7}[DFIOQU])[A-VXY]\d[A-Z][^-\w\d]\d[A-Z]\d\b

Demo

You can also fix yours (at least for the example) with this change:

(?!.*[DFIOQU])[A-VXY][0-9][A-Z].?[0-9][A-Z][0-9]

(except that it accepts a hyphen, which is forbidden)

Demo

But in this case, an explicit pattern may be best:

\b[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z]\s\d[ABCEGHJ-NPRSTV-Z]\d\b

Which completes is 1/4 the steps of the others.

Demo

dawg
  • 98,345
  • 23
  • 131
  • 206
1

This generic code can help you

import re
PIN = input("Enter your Address")
PIN1= PIN.upper()
if (len(re.findall(r'[A-Z]{1}[0-9]{1}[A-Z]{1}\s*[0-9]{1}[A-Z]{1}[0-9]{1}',PIN1)))==1:
print("valid")
    else:
        print("invalid")

As we are taking input from user. So there is many chances that user can type postal code without space, in lower case letters. so this code can help you out with 1) Improper spacing 2)Lower case letter

GRS
  • 41
  • 3