【问题标题】:How To Match Alpha, Numeric and Alphanumeric Values [duplicate]如何匹配字母、数字和字母数字值 [重复]
【发布时间】:2014-02-19 00:11:02
【问题描述】:

我环顾四周,看到人们使用: ^\W\d_ 进行 alpha 匹配但是,如果您先输入一个 alpha 字符,然后在其后面输入数字字符,则匹配不会失败。

这是我正在尝试的代码:

alpha = compile('[a-zA-Z]')
numeric = compile('[0-9]')
alphanumeric = compile('[a-zA-Z0-9]')


def alpha_test():
#Checks for alpha values
    cell = input('Enter an alpha value: ')
    alpha_valid = alpha.match(cell)
    if alpha_valid:
        print('The cell contains only alpha values.\n')
    else:
        print('Invalid. The cell contains other characters.\n')


def numeric_test():
#Checks for numeric values
    cell = input('Enter a numeric value: ')
    numeric_valid = numeric.match(cell)
    if numeric_valid:
        print('The cell contains only numeric values.\n')
    else:
        print('Invalid. The cell contains other characters.\n')


def alphanumeric_test():
#Checks for alphanumeric values
    cell = input('Enter an alphanumeric value: ')
    alphanumeric_valid = alphanumeric.match(cell)
    if alphanumeric_valid:
        print('The cell contains only alphanumeric values.\n')
    else:
        print('Invalid. The cell contains other characters.\n')


alpha_test()
numeric_test()
alphanumeric_test()

也许我对匹配功能提供的内容有错误的看法? 我知道它可以用来匹配电子邮件格式并确保它们是正确的,但我认为它也可以匹配字符输入。

【问题讨论】:

  • [^\W\d_] 表示\w,但不是数字或下划线。与此[a-zA-Z] 相同
  • 您的正则表达式仅匹配 1 个字符。要匹配更多/全部,请使用量词和锚点,例如 ^[a-zA-Z]+$

标签: python regex match


【解决方案1】:

我相信这是我问题的答案 - Regex matches but shouldn't

应该再看看四周,对不起。

【讨论】:

  • 不过很好 - 我在阅读您的代码时没有看到任何明显的内容。
【解决方案2】:

您的正则表达式仅匹配 1 个字符。要匹配更多/全部,请使用量词和锚点,例如 ^[a-zA-Z]+$

【讨论】:

    猜你喜欢
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    相关资源
    最近更新 更多