0

The question concerns writing regular expressions for binary strings.

How do you write one such that it ends with 00 and also another one such that it contains at least three 1's?

2
  • How long are these binary strings? Commented Jul 19, 2013 at 5:54
  • They can be any length. Commented Jul 19, 2013 at 5:55

3 Answers 3

1

Ends with 00:

^[01]*00$

Contains at least three 1s:

^(?=.*(?:0*1){3})[01]*$

Both:

^(?=.*(?:0*1){3})[01]*00$

Explanation:

^        # Start of string
(?=      # Assert that the following could be matched here:
 .*      # Any number of characters
 (?:0*1) # followed by any number of 0s and exactly one 1
 {3}     # three times
)        # End of lookahead
[01]*    # Match any number of ones or zeroes
00       # Match two zeroes
$        # at the end of the string

Since the string may only contain ones and zeroes, we don't actually need to lookahead. The following will work as well (but only in these exact circumstances):

^(?:0*1){3}[01]*00$
Sign up to request clarification or add additional context in comments.

2 Comments

To clarify, does * serve as a link?
* means "0 or more of the preceding token".
0

Alternate solution not using a regex:

private static final BigInteger FOUR = new BigInteger("4");

public boolean binaryStringIsOK(final String input)
{
    final BigInteger b;

    try {
        b = new BigInteger(inputString, 2);
        return b.mod(FOUR).equals(BigInteger.ZERO)
            && b.bitCount() >= 3;
    } catch (NumberException ignored) {
        return false;
    }
}

The "ends with 00" condition means that in base 10, it is a multiple of 4; therefore that the remainder of the integer division by 4 is 0. And the .bitCount() function does the rest.

An alternative to "ends with 00" is to test whether that number logical-and 3 is 0:

// THREE = new BigInteger("3")
b.and(THREE).equals(BigInteger.ZERO)

Comments

0

This is checking regex ...

ends with 00

00$

three 1's

(10*){3}

For full match

^[01]*00$
^0*(10*){3}[01]*$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.