如何在我的程序中修复此正则表达式问题?

时间:2015-10-08 12:31:18

标签: python regex

address = input("Please input the drivers home address (e.g. EH129DN): ")
addresspattern = "[A-Z][A-Z]/d/d/s/d[A-Z][A-Z]"
match = re.search(address, addresspattern)
if match:
    Continue = input ("Do you wish to continue? (Y/N): ")

我不知道为什么这不起作用,但绝对是正则表达式。

4 个答案:

答案 0 :(得分:1)

为了帮助您入门,您可以按如下方式对其进行重组:

ask = 'y'

while ask == 'y':
    address = raw_input("Please input the drivers home address (e.g. EH129DN): ")
    addresspattern = r"[A-Z][A-Z]\d\d\s?\d[A-Z][A-Z]"
    match = re.search(addresspattern, address)

    if match:
        print "Valid"
    else:
        print "Invalid"

    ask = raw_input("Do you wish to continue? (Y/N): ").lower()

给你以下类型的输出:

Please input the drivers home address (e.g. EH129DN): EH12 9DN
Valid
Do you wish to continue? (Y/N): y
Please input the drivers home address (e.g. EH129DN): EH129DN
Valid
Do you wish to continue? (Y/N): y
Please input the drivers home address (e.g. EH129DN): EH1 29DN
Invalid
Do you wish to continue? (Y/N): n

注意,如果您要尝试匹配所有有效的邮政编码,那么您需要调查更实质的正则表达式。我保留了你现有的逻辑,但它现在允许两者之间的可选空间。另外,我已经使用了raw_input(),因为您需要输入文本。

答案 1 :(得分:0)

尝试:

address = input("Please input the drivers home address (e.g. EH129DN): ")
addresspattern = r"[A-Z]{2}\d{3}[A-Z]{2}"
match = re.search(addresspattern, address)
if match:
    Continue = input ("Do you wish to continue? (Y/N): ")
re.search模式的

是第一个参数 EH129DN不包含任何白人空间,因此不需要\s

答案 2 :(得分:0)

尝试使用raw_input代替输入。

import re
address = raw_input("Please input the drivers home address (e.g. EH129DN): ")
addresspattern = "[A-Z][A-Z]/d/d/s/d[A-Z][A-Z]"
match = re.search(address, addresspattern)
if match:
    Continue = raw_input("Do you wish to continue? (Y/N): ")

input和raw_input Differences between `input` and `raw_input`

之间的差异

答案 3 :(得分:0)

您可以尝试这样的事情,它假设总是有2个大写字母,后跟3个数字和2个大写字母

m = re.search(r'[A-Z]{2}[1-9]{3}[A-Z]{2}', addresspattern)
if m:
  #TODO