我正在尝试为数组创建一个正则表达式,以检查数组初始化是否正确:
{1,2,3}
//correct
{1,2,3,,,}
//not correct
Run Code Online (Sandbox Code Playgroud)
这是我现在的正则表达式:
(?!\,\s*\})\{(.*?)\}*
Run Code Online (Sandbox Code Playgroud)
我如何用Java做到这一点?
使用当前正则表达式的探测器是它在之前{没有跟随a的位置查找位置,.在所有给定的字符串中只有一个这样的位置,它位于字符串的开头和{.因此,你的正则表达式只匹配一个字符,即{.
要解决此问题,您需要考虑{...}部件内部字符串的格式:
^\{\d+(?:,\s*\d+)*\}$
Run Code Online (Sandbox Code Playgroud)
\d+匹配第一个值,并(?:,\s*\d+)*匹配其余值.
说明:
^ # beginning-of-the-string anchor
\{ # match a literal { character
\d+ # first element
(?: # beginning of the non-capturing group
, # followed by a comma
\s* # and optional whitespace
\d+ # and one or more elements
)* # make the whole group optional; allow for values like {1}
\} # match a literal } character
$ # end-of-the-string anchor
Run Code Online (Sandbox Code Playgroud)
如果可能存在除数字以外的值,则可以\d使用相应的正则表达式替换.
可视化:
