【问题标题】:Check if a word in a sentence is alphanumeric and return the alnum word检查句子中的单词是否是字母数字并返回 alnum 单词
【发布时间】:2017-09-20 22:42:34
【问题描述】:

我一直在做一个项目,我必须检查用户输入的字符串是否是字母数字。 现在,我已经构建了我的代码,并且有一个函数需要检查是否有任何单词是字母数字。 该程序是让用户输入一个句子以及他的许可证号,这将是字母数字,如“221XBCS”。因此,如果用户输入假设-“我的许可证号是 221124521”而不是 221XBCS,我希望程序停止。 但是我当前的程序假设 re.match 条件始终为真。为什么会这样??

import re
s = input("Please enter here:")

if re.search(r'\bnumber \b',s):
            x = (s.split('number ')[1])
            y = x.split()
            z = y[0]
            print(z)
            if re.match('^[\w-]+$', z):
                print('true')
            else:
                print('False')

现在的输出如下所示:

Please enter here:my license number is 221
is
true

我希望我的程序从输入中获取 alnum 值。就是这样!

【问题讨论】:

  • 看,is^[\w-]+$ 匹配。因此,这是真的。如果需要检查输入是否为字母数字,也可以使用isalnum()。但是我看你还需要支持连字符,那么为什么不使用if re.search(r"\bnumber\s+([\w-]+)", s),如果匹配,则获取group(1) 值?
  • 即使我输入“我的许可证号 22184849”,它仍然适用于该条件。如果我使用 're.search(r"\bnumber\s+([\w-]+)", s)' II 得到 AttributeError: 'str' object has no attribute 'group'
  • @TarakShah,详细说明你的条件:number 这个词是强制性的吗?
  • P.S.我是正则表达式的新手。 :D
  • No @RomanPerekhrest 单词不是强制性的。我希望用户输入他/她的字母数字许可证号

标签: regex python-3.x alphanumeric


【解决方案1】:

我想我理解你的情况:用户应该输入他的许可证号,它应该只包含字母字符AND数字(两者):

内置函数:

s = input("Please enter here:")
l_numbers = list(filter(lambda w: not w.isdigit() and not w.isalpha() and w.isalnum(), s.strip().split()))
l_number = l_numbers[0] if l_numbers else ''

print(l_number)

假设用户输入了My license number is 221XBCS thanks.
输出将是:

221XBCS

【讨论】:

    【解决方案2】:

    对于正则表达式,以相反的方式看待问题通常很有价值。 在这种情况下,查看字符串是否不是纯数字比查看它是否是字母数字更好。

            if re.match('[^\d]', z):
                print('The string is no a pure numerical')
    

    【讨论】:

    • 不适合我。我希望代码检测他/她的许可证的 alnum 值,看起来像这样 '221xncnd22' 现在,使用 re.match('[^\d]', z) 我得到请在此处输入:我的许可证号是221xx 字符串对于任何输入都不是纯数字
    • 如果您想检测句子中没有的内容,请尝试匹配空格。如果要检测句子中的许可证号,请尝试检测固定数字,此处为 8 个 alanum 字符: /(^| )([a-zA-Z0-9]{8})( |$)/
    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 2012-11-02
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多