我正在嘗試匹配模式“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()
uj5u.com熱心網友回復:
用
^[^\W\d_] \s[^\W\d_] \Z
請參閱正則運算式證明。
解釋
--------------------------------------------------------------------------------
^ 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
uj5u.com熱心網友回復:
你有沒有試過編譯:
[a-zA-Z] \s[a-zA-Z]
?
關于@JonSG 的評論:\w適用于任何字母數字。a-zA-Z如果您只需要字母,請將其替換為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334557.html
上一篇:將URL與正則運算式匹配
下一篇:正則運算式:在字串中只符號一次
