首页 > 解决方案 > Javascript 正则表达式与重复模式不匹配

问题描述

Input:"[3, 4]", "[1, 2, 7, 7]"
Input:"[13, 4]", "[1, 2, 3, 6, 14]"
Input: "[5, 5]", "[1, 2, 3]"

\"\s*\[[0-9]\s*\,\s*[0-9]\]\"\s*\,\s*\"\[[0-9]\s*\,

这就是我试图验证上述输入的内容。通过我的尝试,我无法验证字符串的最后一部分。第二个数据数组可以是任意数量的输入。上述正则表达式适用于第二个数组的第一个逗号。在那之后,现在无法为任意数量的输入编写通用表达式。

标签: javascriptregexvalidation

解决方案


如果我理解正确

^\s*"\s*\[\s*[0-9]+\s*(?:\,\s*[0-9]+\s*)*\]\s*"(?:\s*,\s*"\s*\[\s*[0-9]+\s*(?:\,\s*[0-9]+\s*)*\]\s*")*\s*$

https://regex101.com/r/PpZy8I/1

 ^                  # Begin of string     
 \s*                # Leading wsp
 " \s*              # Quote start of array
 \[                 # Array opening
 \s* [0-9]+ \s* 
 (?:                # Optional nesting elements comma plus digits
    \, \s* 
    [0-9]+ \s* 
 )*
 \]                 # Array close
 \s* 
 "                  # Quote end of array    
 
 (?:                # Optional many more arrays
    \s* , \s* 
    " \s* 
    \[ 
    \s* [0-9]+ \s* 
    (?:
       \, \s* 
       [0-9]+ \s* 
    )*
    \] 
    \s* 
    "     
 )*
 \s*                # Trailing wsp
 $                  # End of string

推荐阅读