【问题标题】:python name regex蟒蛇名称正则表达式
【发布时间】:2021-12-08 12:13:18
【问题描述】:

我正在尝试匹配模式“FirstnameSpaceLastname”中的名称,例如 John Doe,只是名字和姓氏之间有一个空格,我该怎么做?下面的代码显示了我尝试过的内容:

user_input = input("Enter you full names: ")
def valid_name():
    #name_regex = re.compile('^[a-zA-Z\\sa-zA-Z]$')
    #name_regex = re.compile('^[a-zA-Z]\s[a-zA-Z]$')
    #name_regex = re.compile('^[a-zA-Z a-zA-Z]+$')
    #name_regex = re.compile('^a-zA-Z\sa-zA-Z$')    
    name_regex = re.compile('^[a-zA-Z a-zA-Z]$')
    nameMatch = re.match(name_regex, user_input)
    if nameMatch:
        print(user_input)
    else:
        print('Enter name in (Firstname Lastname) format')

valid_name()

【问题讨论】:

  • [a-zA-Z a-zA-Z][a-zA-Z ] 相同(请注意,名称的长度和字符可能有很大差异)
  • r"(\w+)\s+(\w+)" 适合你吗?

标签: python python-3.x regex


【解决方案1】:

使用

^[^\W\d_]+\s[^\W\d_]+\Z

regex proof

解释

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [^\W\d_]+                any character of: letters/diacritics (1 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  \s                       whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
  [^\W\d_]+                any character of: letters/diacritics (1 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  \z                       the end of the string

【讨论】:

    【解决方案2】:

    你试过编译吗:

    [a-zA-Z]+\s[a-zA-Z]+
    

    ?

    关于@JonSG 的评论:\w 适用于任何字母数字。如果您只需要字母,请将其替换为 a-zA-Z

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 2018-08-26
      • 1970-01-01
      • 2022-07-06
      • 2021-02-15
      • 1970-01-01
      • 2011-05-11
      • 2019-08-09
      • 2010-09-21
      相关资源
      最近更新 更多