Reputation: 1477
I'm trying to match a coordinate with a python string regex, but I'm not getting a result. I was to see if the input is a valid coordinate definition but I'm not getting the correct match using the code below. Can someone tell me what's wrong?
def coordinate(coord):
a = re.compile("^(([0-9]+), ([0-9]+))$")
b = a.match(coord)
if b:
return True
return False
Currently, it's returning false even if I pass in (3, 4)
which is a valid coordinate.
Upvotes: 0
Views: 173
Reputation:
This works:
from re import match
def coordinate(coord):
return bool(match("\s*\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*\)\s*$", coord))
It is also quite powerful, having the ability to handle negative numbers, fractions, and an optional space between the numbers.
Below is a breakdown of the Regex pattern:
\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
Upvotes: 3
Reputation: 1530
It seems to me that you do not properly escape the parenthesis that makes the coordinate syntax. In regex, parenthesis are special characters used for grouping and capturing. You need to escape them this way:
>>> a = re.compile("^\(([0-9]+), ([0-9]+)\)$")
>>> a.match("(3, 4)")
<_sre.SRE_Match object at 0x0000000001D91E00>
Upvotes: 0
Reputation: 12076
You need to escape the parentheses that you are trying to match. Try using the following:
^(\([0-9]+,\s[0-9]+\))$
Upvotes: 0