代码之家  ›  专栏  ›  技术社区  ›  Tarak Shah

检查句子中的单词是否为字母数字,并返回alnum单词

  •  0
  • Tarak Shah  · 技术社区  · 7 年前

    现在,我已经构建了我的代码,有一个函数需要检查任何单词是否为字母数字。 但我目前的计划是假设重新。匹配条件始终为true。为什么会这样??

    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值。这就是全部!

    2 回复  |  直到 7 年前
        1
  •  0
  •   RomanPerekhrest    7 年前

    我想我理解你的条件:用户应该输入他的许可证号码,该号码只能包含字母字符

    具有内置功能:

    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
  •  0
  •   Gaétan RYCKEBOER    7 年前

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

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