正则表达式:长度是3的倍数的二进制字符串?

3
我该如何编写一个正则表达式,使其匹配二进制字符串且长度是3的倍数(包括空字符串)? 例如: 010 是正确的 0101 是错误的。
3个回答

7

将正则表达式包裹在^$内,以使其对整个字符串进行匹配。

^([01]{3})*$

很好,简洁明了,我一直注意并喜欢你的正则表达式风格。点赞 :) - zx81

4
以下应该可以正常工作:
^(?:[01]{3})*$

编辑:为了优化,可以使用非捕获组。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接