如何编写正则表达式来验证4字符串作为非零二进制数?

eri*_*ons 2 javascript php regex

我有一个字符串,例如1001,它需要正好4个字符,并且可以任意组合01,但不是所有的零(所有的人就可以了).

我想到了:

^[01]{4}$
Run Code Online (Sandbox Code Playgroud)

不会工作,因为它接受 0000

我将使用PHP或JavaScript来执行此操作.

只需添加一个细节.

我将使用它来验证多选择调查问卷的答案,然后进入数据库,因此字符串的长度为N,具体取决于问题的选择数量.

所以提供一般解决方案的功能会很棒.

Bra*_*raj 5

它应该工作

^(?!0000)[01]{4}$
Run Code Online (Sandbox Code Playgroud)

DEMO

注意:使用gm作为改性剂

阅读更多关于实际匹配字符的Lookahead和Lookbehind Zero-Length Assertions,然后放弃匹配,仅返回结果:匹配或不匹配.

模式说明:

  ^                        the beginning of the string
  (?!                      look ahead to see if there is not:
    0000                     '0000'
  )                        end of look-ahead
  [01]{4}                  any character of: '0', '1' (4 times)
  $                        end of the string
Run Code Online (Sandbox Code Playgroud)