简体   繁体   English

正则表达式,其中二进制数没有 1 和 0 直接跟随

[英]Regular expression where Binary numbers have no ones and zeros follow each other directly

Hi I'm trying to find a regular expression where a binary number has no ones and zeros follow each other directly.您好,我正在尝试找到一个正则表达式,其中二进制数没有 1,而 0 直接相互跟随。 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"这是我用于测试的字符串:“10101010”

The expression should check like this:表达式应该像这样检查:

10101010 --> is allowed 10101010 --> 允许

10010101 --> is not allowed 10010101 --> 不允许

But this expression always returns false even when the binary number is allowed and I can't find the cause of it.但是即使允许二进制数,这个表达式也总是返回 false,我找不到它的原因。 Would be nice if you could help me.如果你能帮助我就好了。

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.它表示有效输入以可选的 0 开头,后跟零个或多个10序列,最后可选地还有一个 1。

This will also match empty input.这也将匹配空输入。 If an empty input should be rejected, then add a \b :如果应拒绝空输入,则添加\b

^\b0?(10)*1?$

Make sure to escape the backslash when placing this in a string literal:将其放在字符串文字中时,请确保转义反斜杠:

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

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

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