这有效:
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