我该如何编写一个正则表达式,使其匹配二进制字符串且长度是3的倍数(包括空字符串)?
例如:
010 是正确的
0101 是错误的。
将正则表达式包裹在^
和$
内,以使其对整个字符串进行匹配。
^([01]{3})*$
^(?:[01]{3})*$
编辑:为了优化,可以使用非捕获组。
以下是我的建议:
^(?:[01]{3})*$
它符合所需的模式,但不捕获括号中的组。
说明:
^ // matches beginning of the string
(?: // opens a non-capturing group
[01] // a symbol class, which could only contain 0's or 1's
{3} // repeat exactly three times
) // closes the previously opened group
* // repeat [0, infinity] times
$ // matches the end of the string