2013-11-05 53 views
0

我想匹配一個Python字符串正則表達式的座標,但我沒有得到結果。我想看看輸入是否是一個有效的座標定義,但我沒有使用下面的代碼得到正確的匹配。有人能告訴我什麼是錯的嗎?在python正則表達式中匹配表達式

def coordinate(coord): 
    a = re.compile("^(([0-9]+), ([0-9]+))$") 
    b = a.match(coord) 
    if b: 
     return True 
    return False 

目前,它的返回false即使我通過在(3, 4)這是一個有效的座標。

+2

一開始,你想'B = a.match(座標)','不是B = re.match(座標)'。 –

+1

您需要轉義正則表達式字符串中的一些括號。你有一些parens在那裏,你的意思是字面parens,但他們將被解釋爲一個捕獲組。 –

+0

@TimPeters,但後來我期望'TypeError'因爲不正確的參數...所以我真的不知道我們是否正在處理這裏的實際代碼... –

回答

3

這工作:

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 
+0

也許可選空間會更好。很好的解釋! – aIKid

+0

'\ s?'對我來說似乎很奇怪 - 它匹配一個空格,或一個製表符,或一個換行符,或任何其他單個空格字符,但不是兩個空格。匹配標籤但不是多個空格感覺不一致。如果我編寫正則表達式,我可能會選擇'\ 040?'或'\ s *'。 –

+0

考慮一個可選的前導和結束空間;即:''\ s * \( - ?\ d +(?:\。\ d +)?,\ s? - ?\ d +(?:\。\ d +)?\)\ s * $「' – dawg

0

您需要跳過您嘗試匹配的圓括號。嘗試使用以下內容:

^(\([0-9]+,\s[0-9]+\))$ 
0

在我看來,您並沒有正確地轉義使座標語法的括號。在正則表達式中,括號是special characters used for grouping and capturing。你需要逃離他們這樣說:

>>> a = re.compile("^\(([0-9]+), ([0-9]+)\)$") 
>>> a.match("(3, 4)") 
<_sre.SRE_Match object at 0x0000000001D91E00>