简体   繁体   English

如何通过正则表达式检查字符串

[英]How to check the string by regex

There is a such string - 1,2,3;45,25,65;4,2,78 . 有这样的字符串1,2,3;45,25,65;4,2,78 And I want to check it by regex such that: 我想通过正则表达式进行检查,例如:

  • Number of digits of substring before the semicolon is constant for every substring before the semicolon. 对于分号之前的每个子字符串,分号之前的子字符串的位数是恒定的。 For example in the string above this number is 3. 例如,在该数字上方的字符串中为3。
  • String does not end by semicolon ( ; ). 字符串不以分号( ; )结尾。

Examples of strings: 字符串示例:

  • 1,2,3;3,4,7 matched 1,2,3;3,4,7匹配
  • 1,2,3 matched 1,2,3匹配
  • 1,2;3,4; does not match (because of ; at the end) 不匹配(因为;结尾)

If you want to do this with regexp, you are forced to specify the constant. 如果要使用regexp进行此操作,则必须指定常数。 This is the generic regex: 这是通用正则表达式:

^\d+(,\d){n-1}(;\d+(,\d){n-1})*$

Where n-1 is your constant subtracting 1 (in the example above, n-1 = 2 ). 其中n-1是您的常数减去1(在上面的示例中, n-1 = 2 )。 See demo . 参见演示


The iterative method instead always work: 相反,迭代方法始终有效:

def my_match(s) :
  k = None
  for arr in s.split(";") :
    length = len(arr.split(","))
    if k :
      if k != length : return False
    else :
      k = length
  return True

input = "1,2,3;45,25,65;4,2,78" # we assume that the input synthax is correct
print my_match(input)

If you don't assume that the input synthax is correct, use first Tim Biegeleisen's regex (something like ^\\d+(,\\d)*(;\\d+(,\\d)*)*$ ) for validating and then the method above. 如果您不认为输入的语法正确,请先使用Tim Biegeleisen的正则表达式(例如^\\d+(,\\d)*(;\\d+(,\\d)*)*$ )进行验证,然后使用方法以上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM