Home > Enterprise >  Regular expression where Binary numbers have no ones and zeros follow each other directly
Regular expression where Binary numbers have no ones and zeros follow each other directly

Time:11-27

Hi I'm trying to find a regular expression where a binary number has no ones and zeros follow each other directly. This is the regular expression I have:

public static boolean isBin2(String bin2) {
        Pattern regexBinary2 = Pattern.compile("(01*01)*");

        Matcher matcher = regexBinary2.matcher(bin2);
        return matcher.matches();
    }

This is the String I'm using for my tests: "10101010"

The expression should check like this:

10101010 --> is allowed

10010101 --> is not allowed

But this expression always returns false even when the binary number is allowed and I can't find the cause of it. Would be nice if you could help me.

CodePudding user response:

Here is a regular expression that doesn't use look around:

^0?(10)*1?$

It says that valid input starts with an optional 0, is followed by zero or more sequences of 10, and optionally has one more 1 at the end.

This will also match empty input. If an empty input should be rejected, then add a \b:

^\b0?(10)*1?$

Make sure to escape the backslash when placing this in a string literal:

    Pattern regexBinary2 = Pattern.compile("^\\b0?(10)*1?$");

CodePudding user response:

I can never understand why use regular expressions for such a simple task.

Regular expressions:

  • It's hard to write
  • It's hard to debug
  • It's very, very hard to read ("^(?!.*([01])\\1)[01] " - WTF?!)
  • It's hard to use correctly

For example, you create a new instances of Pattern and Matcher every time you call a function. This is definitely not correct.

A simple cycle can be written in 30 seconds and solve this task perfectly.

public static boolean isBin2(@NotNull String bin2) {
        if (bin2.length() < 2) return true;

        int i = 1;
        while (i < bin2.length()) {
            if (bin2.charAt(i) == bin2.charAt(i - 1)) return false;
            i  ;
        }
        return true;
    }
  • Related