验证用以下基于正则的模式匹配的逗号分隔坐标的用户输入



我有一个问题,用户可以在括号内输入任何数量的(x,y)坐标。例如,用户可以输入(1,1) (1,2) (1,3)

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

我想要一个通用模式匹配来检查用户输入的输入是否有效。仅当输入遵循上述格式时才有效。也就是说,(x,y)s(a,b)s(c,d)。我是Regex匹配的新手,我尝试了(\(d,d\)s){1,}。这似乎不起作用。另外,在上次坐标条目之后不应在那里。有人可以帮我如何得到这个吗?

预先感谢。

如果要验证整个输入,我建议使用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

整个字符串匹配,或者什么都不匹配。默认情况下,re.match从始于开始,如果字符串有效,将返回match对象,否则Nonebool结果将用于评估此表达的真实性。

请注意,已使Whitespace字符已成为可选的,以简化表达式。如果您想要严格的匹配,建议您查看Dyz的答案。


REGEX详细信息

(        # 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

我提供了对多位数数字的支持,以防万一:

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

您可以尝试以下方法:

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

最新更新