這工作:
from re import match
def coordinate(coord):
return bool(match("\s*\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*\)\s*$", coord))
這也是相當強大,必須處理負數,分數和數量之間的可選空間的能力。
下面是正則表達式模式的崩潰:
\s* # Zero or more whitespace characters
\( # An opening parenthesis
\s* # Zero or more whitespace characters
-? # An optional hyphen (for negative numbers)
\d+ # One or more digits
(?:\.\d+)? # An optional period followed by one or more digits (for fractions)
\s* # Zero or more whitespace characters
, # A comma
\s* # Zero or more whitespace characters
-? # An optional hyphen (for negative numbers)
\d+ # One or more digits
(?:\.\d+)? # An optional period followed by one or more digits (for fractions)
\s* # Zero or more whitespace characters
\) # A closing parenthesis
\s* # Zero or more whitespace characters
$ # End of the string
一開始,你想'B = a.match(座標)','不是B = re.match(座標)'。 –
您需要轉義正則表達式字符串中的一些括號。你有一些parens在那裏,你的意思是字面parens,但他們將被解釋爲一個捕獲組。 –
@TimPeters,但後來我期望'TypeError'因爲不正確的參數...所以我真的不知道我們是否正在處理這裏的實際代碼... –