Validating user input for comma separated coordinates using regular expression pattern matching

I have a problem where the user can enter any number of coordinates (x, y) in parentheses. For example, User A can enter(1,1) (1,2) (1,3)

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

I want the generic template to match the check if the user input is valid. Input is valid only if it matches the format specified above. That is (x,y)\s(a,b)\s(c,d). I am new to regex matching and I tried how (\\(\d,\d\\)\s){1,}. This does not seem to work. In addition, the space should not be after the last coordinated recording. Can someone help me how to do this?

Thanks in advance.

+4
source share
3 answers

I have 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
+2
source

If you want to check all input, I would suggest using 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 line matches, or nothing matches. By default, it re.matchstarts from the beginning and returns an object matchif the string is correct, or Noneotherwise. The result boolwill be used to evaluate the truth of this expression.

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


Regular Expression 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
+4
source

You can try the following:

import re

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

Source: https://habr.com/ru/post/1686165/


All Articles