I'm working on a program that takes the input in a particular format: example "(1,2)(2,3)(4,3)". They are coordinates and there can be infinitely many coordinates "(1,2)(2,3)(4,3)...(a,b)". I'm writing a function "checkFormat(str)" that returns true if the format is satisfied. I've tried writing a function without the use of regex but it proved too difficult. Need help with the regex expression.
CodePudding user response:
Use ^
and $
to match the whole input. in between is one or more set of (...)
filled with digits.
Assuming coordinates are integer and no extra space in between:
^((\((\d) \,(\d) )\)) $
if /-
is allowed and 0
has no sign and could not be extended (00
or 01
not accepted)
^(\(([-\ ]?[1-9]\d*|0)\,(([-\ ]?[1-9]\d*)|0)\)) $
If decimal numbers are included:
^(\(([-\ ]?[1-9]\d*|0)([.]\d )?\,(([-\ ]?[1-9]\d*)|0)([.]\d )?\)) $
To check if the input match or not:
import re
pattern=r'^(\(([-\ ]?[1-9]\d*|0)([.]\d )?\,(([-\ ]?[1-9]\d*)|0)([.]\d )?\)) $'
input='(0,2)(1,2)'
result=bool(re.match(pattern,input))