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

2024-09-30 14:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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): ")

我不知道为什么这不起作用,但它肯定是正则表达式


Tags: thereyouhomeinputsearchifaddress
3条回答

尝试:

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

尝试使用原始输入代替输入

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): ")

输入和原始输入之间的差异Differences between `input` and `raw_input`

为了让您开始,您可以按以下方式对其进行重组:

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(),因为您需要文本输入

相关问题 更多 >

    热门问题