简体   繁体   中英

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."

I gave my answer as (000|1)$ which was marked wrong. 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:

     ^[01]*(000|1)$ 
  2. There may be no leading 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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