简体   繁体   English

正则表达式的二进制数可被8或奇数除

[英]Regex for binary number divisible by 8 OR odd

"Write a regular expression that describes all strings of zeroes and ones representing binary numbers that are either odd or divisible by 8. The numbers may not have any leading zeros." “编写一个正则表达式,描述所有的零字符串和一个表示二进制数字的字符串,这些二进制数字可以是奇数或可被8整除。数字可能没有任何前导零。”

I gave my answer as (000|1)$ which was marked wrong. 我给出的答案是(000|1)$ ,它被标记为错误。 I cannot see the reason why. 我看不出原因。 Please explain! 请解释! Thanks in advance. 提前致谢。

You forgot two of the requirements. 您忘记了两个要求。

  1. It must contain only 1 s and 0 s: 它只能包含1秒和0秒:

     ^[01]*(000|1)$ 
  2. There may be no leading 0 s: 可能没有前导0 s:

     ^(?!0)[01]*(000|1)$ 

    If lookaheads are not allowed, it becomes a bit trickier: 如果不允许先行,则将变得有些棘手:

     ^1[01]*(000|1)$|^1$ 

Another addition, if you are allowed to use only the regular expression constructs that are available in "theoretical" regular expressions (alternation, group and repetition), it would look like this (anchors are implicit in this case): 另一个补充,如果只允许使用“理论”正则表达式(交替,分组和重复)中可用的正则表达式构造,则它看起来像这样(锚在这种情况下是隐式的):

1(0|1)*(000|1)|1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM