buddingengineer
buddingengineer

Reputation: 95

Validate user input of comma separated coordinates with regex-based pattern matching

I have a problem where the user can input any number of (x,y) co-ordinates within parentheses. For example, User A can input (1,1) (1,2) (1,3)

User B : (1,1)
User C : (3,2) (5,5) (6,1)

I want a generic pattern matching to check if the input entered by the user is valid. Input is valid only if it follows the above format. That is, (x,y)\s(a,b)\s(c,d). I am new to regex matching and I tried like (\\(\d,\d\\)\s){1,}. This does not seem to work. Also, space should not be there after the last co-ordinate entry. Can someone help me how to get this?

Thanks in advance.

Upvotes: 4

Views: 978

Answers (3)

Ajax1234
Ajax1234

Reputation: 71461

You can try this:

import re

s = "(1,1) (1,2) (1,3)"
if re.findall("(\(\d+,\d+\)\s)|(\(\d+,\d+\)$)", s):
   pass

Upvotes: 0

DYZ
DYZ

Reputation: 57085

I included support for multi-digit numbers, just in case:

pattern = r"(\(\d+,\d+\)\s)*\(\d+,\d+\)$"
re.match(pattern, "(1,1) (1,2) (1,3)")
#<_sre.SRE_Match object; span=(0, 17), match='(1,1) (1,2) (1,3)'>
re.match(pattern, "(1,1)")
#<_sre.SRE_Match object; span=(0, 5), match='(1,1)'>
re.match(pattern, "(1,1) (1,2) (1,3) ") # no match
re.match(pattern, "(1,1) (1,2)(1,3)") # no match

Upvotes: 2

cs95
cs95

Reputation: 402814

If you want to validate the whole input, I'd suggest the use of re.match.

>>> pattern = re.compile('(\(\d+,\d+\)\s*)+$')    
>>> def isValid(string):
...     return bool(pattern.match(string.strip()))
... 
>>> string = '(1,1) (1,2) (1,3)'
>>> isValid(string)
True

Either the whole string matches, or nothing matches. By default, re.match starts from the beginning, and will return a match object if the string is valid, or None otherwise. The bool result will be used to evaluate the truthiness of this expression.

Note that the whitespace character has been made optional to simplify the expression. if you want a strict matching, I recommend looking at DYZ' answer.


Regex Details

(        # capturing group 
    \(       # opening paren 
    \d+      # 1 or more digits
    ,        # comma
    \d+      
    \)       # closing paren
    \s*      # 0 or more whitespace chars
)+       # specify repeat 1 or more times
$        # end of string

Upvotes: 4

Related Questions