我试图匹配模式"FirstnameSpaceLastname"约翰·多伊,只有名字和姓氏之间加个空格,我该怎么写呢?下面的代码显示了我所尝试的:
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-Zsa-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()
使用
^[^Wd_]+s[^Wd_]+Z
参见正则表达式证明。
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
[^Wd_]+ any character of: letters/diacritics (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
s whitespace (n, r, t, f, and " ")
--------------------------------------------------------------------------------
[^Wd_]+ any character of: letters/diacritics (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
z the end of the string
您是否尝试过编译:
[a-zA-Z]+s[a-zA-Z]+
?
关于@JonSG的评论:w
是任何字母数字。如果您只需要字母,则将其替换为a-zA-Z
。